Forzar Descarga Ficheros en PHP

Una de los problemas más habituales que nos encontramos es el poder forzar la descarga de un determinado fichero desde el navegador del cliente, evitando así que lo abra.

Para ello podemos usar la siguiente función en PHP.

function force_download($file)
{
    if ((isset($file))&&(file_exists($file))) {
       header("Content-length: ".filesize($file));
       header('Content-Type: application/octet-stream');
       header('Content-Disposition: attachment; filename="' . $file . '"');
       readfile("$file");
    } else {
       echo "No hay un fichero seleccionado";
    }
}

 

1.533 responses to “Forzar Descarga Ficheros en PHP

  1. jordan 1 off white

    I am often to running a blog and i really appreciate your content. The article has actually peaks my interest. I am going to bookmark your website and preserve checking for brand spanking new information.

  2. paul george shoes

    An fascinating discussion is price comment. I feel that it is best to write more on this subject, it won’t be a taboo topic but typically people are not enough to talk on such topics. To the next. Cheers

  3. jordan sneakers

    Oh my goodness! a tremendous article dude. Thanks Nonetheless I am experiencing subject with ur rss . Don抰 know why Unable to subscribe to it. Is there anybody getting identical rss drawback? Anybody who knows kindly respond. Thnkx

  4. supreme new york

    Aw, this was a really nice post. In thought I would like to put in writing like this additionally ?taking time and actual effort to make a very good article?but what can I say?I procrastinate alot and certainly not appear to get one thing done.

  5. golden goose

    There are some attention-grabbing deadlines in this article however I don抰 know if I see all of them heart to heart. There’s some validity however I will take maintain opinion until I look into it further. Good article , thanks and we want extra! Added to FeedBurner as nicely

  6. supreme

    I抦 impressed, I must say. Actually hardly ever do I encounter a blog that抯 each educative and entertaining, and let me let you know, you may have hit the nail on the head. Your thought is outstanding; the problem is something that not sufficient people are speaking intelligently about. I’m very completely satisfied that I stumbled across this in my search for something regarding this.

  7. off white shoes

    Aw, this was a very nice post. In concept I would like to put in writing like this moreover ?taking time and precise effort to make a very good article?but what can I say?I procrastinate alot and by no means seem to get something done.

  8. kyrie 4

    I am usually to running a blog and i really admire your content. The article has really peaks my interest. I’m going to bookmark your site and hold checking for new information.

  9. supreme clothing

    After research a couple of of the blog posts on your website now, and I really like your means of blogging. I bookmarked it to my bookmark website list and shall be checking back soon. Pls try my web site as effectively and let me know what you think.

  10. jordan 12

    I抎 should verify with you here. Which is not one thing I often do! I enjoy reading a submit that can make folks think. Also, thanks for allowing me to comment!

  11. steph curry shoes

    After research a few of the blog posts on your web site now, and I really like your way of blogging. I bookmarked it to my bookmark website list and shall be checking again soon. Pls take a look at my web site as well and let me know what you think.

  12. moncler

    The following time I learn a blog, I hope that it doesnt disappoint me as a lot as this one. I mean, I know it was my option to learn, however I truly thought youd have one thing fascinating to say. All I hear is a bunch of whining about something that you would repair if you happen to werent too busy in search of attention.

  13. adidas yeezy

    An interesting discussion is worth comment. I believe that you need to write more on this subject, it might not be a taboo subject however generally people are not sufficient to speak on such topics. To the next. Cheers

  14. yeezy

    The next time I learn a weblog, I hope that it doesnt disappoint me as much as this one. I mean, I know it was my option to read, however I actually thought youd have one thing fascinating to say. All I hear is a bunch of whining about one thing that you could repair should you werent too busy in search of attention.

  15. superslot เล่น ผ่าน เว็บ

    superslot เล่น ผ่าน เว็บ เว็บไซต์สล็อตออนไลน์ รูปแบบใหม่ ซุปเปอร์สล็อตเอ็กซ์ดี มาแรง กับ pg-slot.game ที่มาแรงที่สุดในขณะนี้ ทางพวกเราเป็นคนที่ให้บริการเกม พีจีสล็อต ที่สนุกที่สุด

  16. majorsite

    I’m writing on this topic these days, majorsite, but I have stopped writing because there is no reference material. Then I accidentally found your article. I can refer to a variety of materials, so I think the work I was preparing will work! Thank you for your efforts.

  17. seads

    Генетический фактор является определяющим для мужского облысения, но немаловажен и для объяснении причин женского. Трихологи советуют трезво оценить состояние шевелюры папы и дедушки (а также бабушки) — если они рано начали терять волосы, скорее всего, вы тоже можете быть в группе риска. Все права защищены © brovinka.ru, 2022 Нарушения в работе нервной системы. Психоэмоциональное здоровье человека оказывает непосредственное воздействие на весь организм. Длительное пребывание в стрессовом состоянии и появление депрессии приводит к ослаблению волосков бровей, которые начинают развиваться гораздо медленнее, подвергаются пигментации. Проверь уровень витаминов Это препарат для заживления ран, восстановления кожи, содержащий витамины А, Е, К и бета-каротин, а это значит, что он очень полезен для волос – питает, увлажняет, снимает воспаление, является антиоксидантом. Его можно добавлять в любые ваши маски для обогащения их витаминами или просто смешать 2 чайных ложки Аекола и любого масла. Стоимость от 150 р. https://viking-educate.com/community/profile/geraldinemattes/ Ничего не найдено Акции и предложения от нас Нет в наличии с 25.02.2020 Ультразвуковой массаж для восстановления свежести и цвета кожи, подтяжки мимических морщин. • Средняя продолжительность процедуры: 20-60 минут. • Стоимость: 450 – 950 рублей за процедуру. • Количество требуемых процедур: 10-15. Данная процедура очень эффективна в комплексном… Хотите иметь красивые, длинные пышные ресницы? • Средняя продолжительность процедуры: от 60 минут. • Стоимость: от 900 рублей. Уход за лицом – Наращивание ресниц – это и красиво, и практично: не… Обзор сыворотки для ресниц Eveline 3 в1 смотрите в следующем видео. в наличии 8 шт Активнодействующим компонентом средства выступает масло арганы, которое интенсивно питает, увлажняет ресницы и зону роста ресниц, стимулирует рост ресниц, обеспечивает ресничкам эластичность, гладкость, ошеломляющую длину и шикарный объем. Продукт оснащен удобной, мягкой кистью, которая отлично прокрашивает каждый волосок.    

  18. ezslot

    ezslot เว็บระบบอัตโนมัติ ผู้ให้บริการสล็อตออนไลน์ ที่มีความน่าเชื่อถือ ที่สุด บริการ ผ่านเว็บตรง สล็อต ปลอดภัย100% ทำให้ผู้เล่นได้ มีส่วนร่วมกับ เว็บสล็อตออนไลน์ทำให้ผู้เล่นได้

  19. safetoto

    I have been looking for articles on these topics for a long time. safetoto I don’t know how grateful you are for posting on this topic. Thank you for the numerous articles on this site, I will subscribe to those links in my bookmarks and visit them often. Have a nice day

  20. ทดลองเล่น บา คา ร่า

    ทดลองเล่น บา คา ร่า สูตรบาคาร่า ของพวกเรา เป็นค่าย pg slot เกมคาสิโน ออนไลน์ ที่สุดยอดในประเทศไทย ให้บริการ แบบคาสิโนสด ด้วยผู้เชี่ยวชาญ มีคณะทำงาน มืออาชีพ ดูแลท่าน ไม่มีสะดุด

  21. totosite

    Looking at this article, I miss the time when I didn’t wear a mask. totosite Hopefully this corona will end soon. My blog is a blog that mainly posts pictures of daily life before Corona and landscapes at that time. If you want to remember that time again, please visit us.

  22. casinosite

    When I read an article on this topic, casinosite the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?

  23. Stewartire

    рассвет крым санаторий актер на карте сочи
    ибис стайлс отели липецка пятигорский институт курортологии
    голубая лагуна отель анапа туры в ноябре цены калипсо красная поляна

  24. Stewartagn

    гостиницы великий устюг бутик отель вилла италия краснодар
    рио де кавказ ессентуки где находится резиденция спа в репино отель спа комплекс путевка в алушту
    отель самсон в петергофе гостиница скайпоинт шереметьево дом отдыха питиус абхазия

  25. Stewartjya

    санаторий долина нарзанов кисловодск адрес sanremo кабардинка
    отель николь пермь отдых в архызе 2022 цены санаторий исток кисловодск официальный сайт
    солнечный дом отдыха абхазия отель хоста в хосте дома отдыха все включено в подмосковье

  26. Stewartoco

    отель миллениум тульская область отзывы о сестрорецком курорте
    дивеево нб гостиница официальный сайт отель севан плаза ростов на дону загородный комплекс петушки
    panorama by mercury красная поляна букинг карловы вары гостиница звездочка барнаул

  27. Stewartgrn

    отель korston казань найти путевку
    гостиница тета кропоткин гостевые дома с бассейном в анапе база отдыха стрелинка
    гостиница первоуральск санаторий росинка беларусь отдых в крыму гостиница

  28. Stewartacp

    пансионат охотник янаис отель адлер
    санаторий кавминводы отели уссурийска отель вилла елена крым
    санаторий голден в алуште официальный сайт плес ивановская область гостиницы недорого замок короля воронеж

  29. pg

    pg ยอดเยี่ยมเกมออนไลน์สล็อตบนมือถือแบบใหม่ปัจจุบันของโลกสมัครเล่น PG SLOT วันนี้ไม่มีเบื่อไม่ซ้ำซากในแบบการเล่นเดิมๆอีกต่อไปเป็นเกมสล็อตที่แจ๊คพอตแตกหลายครั้งที่สุดลองเลย

  30. VederTwtpsp

    гостиница татарстан в казани бургас сочи на карте
    отель антик москва климашкина отдых в подмосковье 5 звезд все включено пансионат поляны управления делами президента официальный
    шведский стол уфа канавинский хостел ольгино гостиница

  31. VederTwtall

    славянка отель анапа официальный сайт санаторий крым партенит
    путевки купить краснодарский край п витязево бригантина береговое
    алушта тур отель del mare джемете гостиницы и отели краснодара

  32. VederTwtkij

    ибис 3 казань санаторий нехама
    дельфин санаторий адлер официальный сайт мыс видный корпус олимп база отдыха солнечный берег ярославль
    северный кавказ курорты вилла коронелли феодосия гостиница акварели санкт петербург

  33. VederTwtjdd

    санатории в пицунде wellness park hotel gagra 5
    санаторий барнаул официальный сайт семья курган горячие отель герцен хаус
    архипо осиповка кирпичная 6 талассотерапия показания санаторий машук акватерм отзывы

  34. VederTwtgzg

    военный санаторий сочи курорты санатории россии
    багатель отель марсель туапсе ооо славянка анапа
    отель международный отель альпийская долина алушта санаторий виктория кисловодск официальный

  35. VederTwtwps

    пансионат ялта спб гостиница с завтраком
    детский санаторий салют инн сокольники бутик отель родники 5
    медвежьегорск гостиница малая медвежка грот дианы пятигорск пансионаты на черном море с питанием

  36. VederTwtosn

    mpl travel com горящие путевки гостиничный комплекс романтик
    дом отдыха воронцово хостел bedandbike отель каспий махачкала
    эсмеральда витязево курорт инфо сестрорецк отели в адлерском районе сочи

  37. VederTwtqbb

    отель делайт москва таганская база туров для турагентств
    отель кипарис геленджик официальный сайт марриотт сочи отзывы абхазия для детей
    санаторий кругозор кисловодск отзывы отель ибис чебоксары санаторий bridge resort сочи

  38. VederTwtfbf

    отель винтаж новый свет официальный сайт имеретинский сочи официальный
    дом отдыха в гаграх абхазия tes отель евпатория ирее
    снять гостевой дом в евпатории 2021 хочу на юга адлер частный сектор отели в судаке все включено

  39. DavidJax

    видео онлайн клипы николай гута арктика мини кондиционер купить в москве https://homeboxx.ru/post/1 фильм виртуальная любовь смотреть онлайн бесплатно в хорошем качестве

  40. stocks trading online

    Hi there! Do you know if they make any plugins to protect against hackers?I’m kinda paranoid about losing everything I’ve worked hard on.Any recommendations?Stop by my blog post – ACV Advanced Gummies Review

  41. buy shares

    I’d like to thank you for the efforts you have put in penning this blog. I am hoping to see the same high-grade content from you in the future as well. In truth, your creative writing abilities has motivated me to get my very own blog now 😉

  42. trade shares

    Very thoughtful content, I didn’t know one could write so efficiently on this topic so effortlessly.Very well crafted and also portrayed in a very precise manner.seo digital agency

  43. this website

    Howdy! I’m at work surfing around your blog from my new apple iphone! Just wanted to say I love reading through your blog and look forward to all your posts! Carry on the superb work!

  44. explore

    whoah this blog is excellent i really like studying your articles.Keep up the great work! You understand, a lot of individualsare looking around for this information, you can aid them greatly.

  45. Jean Greenwood

    Hi there, its fastidious article regarding media print, we all be familiar with media is a fantastic sourceof data.

  46. sim vina

    I am curious to find out what blog platform youhappen to be utilizing? I’m experiencing some minor security issues with my latest blog and I’d like to find something more safeguarded.Do you have any suggestions?

  47. ayurvedic medicine

    Hello! I know this is kind of off topic but I was wondering if you knew where I could find a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one? Thanks a lot!

  48. C_ARSCC_2208 exam guide

    Oh my goodness! Amazing article dude! Thanks, However I am having issues with your RSS. I don’t know why I cannot subscribe to it. Is there anyone else having the same RSS issues? Anybody who knows the solution can you kindly respond? Thanks!!

  49. Jerry Graham

    Right now it sounds like BlogEngine is the preferred blogging platform out there right now. (from what I’ve read) Is that what you’re using on your blog?

  50. Evropski univerzitet Kallos

    Oh my goodness! Awesome article dude! Thank you, However I am having issues with yourRSS. I don’t know the reason why I can’t join it. Is there anyone else having the sameRSS problems? Anyone that knows the solution will you kindly respond?Thanx!!

  51. Raspored nastave I i II ciklus

    Very nice info and right to the point. I don at know if this is in fact the best place to ask but do you people have any thoughts on where to get some professional writers? Thanks in advance

  52. poker88

    Normally I do not read article on blogs, however I would like to say that this write-up very compelled me to take a look at and do it! Your writing style has been surprised me. Thank you, quite nice article.

  53. slot machine

    slot machine ที่ได้รับความนิยมชั้น 1 ของทวีปเอเชีย PG SLOT ที่มากับระบบฝาก เบิกเงินอัตโนมัติ เร็วทันใจมากขึ้นเพื่อการทำ แจ็คพอตแตก ก็เลยเอามาให้บริการ บนเว็บ เกมสล็อตออนไลน์

  54. Hoc pha tra sua

    hello!,I really like your writing so a lot! share we keep up a correspondence more approximately your article on AOL? I need an expert in this space to resolve my problem. May be that’s you! Taking a look forward to see you.

  55. Buy Ethereum

    Nice post. I was checking constantly this blog and I am impressed!Very useful information particularly the last part 🙂 I care for such information much.I was seeking this particular info for a long time. Thank you and best of luck.

  56. Market Analysis

    You can certainly see your enthusiasm within the work you write. The arena hopes for even more passionate writers such as you who aren’t afraid to mention how they believe. At all times go after your heart.

  57. Thi cong quan cafe

    An attention-grabbing discussion is worth comment. I think that you should write more on this topic, it may not be a taboo topic however usually persons are not enough to talk on such topics. To the next. Cheers

  58. Lisa Sutton

    I’m really enjoying the design and layout of your blog. It’s a very easy on the eyeswhich makes it much more enjoyable for me to come here and visit more often. Did youhire out a developer to create your theme? Excellent work!

  59. Edith Rhodes

    Hey There. I found your blog using msn. This is a very well written article. I’ll be sure to bookmark it and return to read more of your useful information. Thanks for the post. I will certainly return.

  60. online tutoring

    I’m training to be an engineer propranolol treatment of ptsd Sensors recognize the passengers’ hands and offer them user interfaces within convenient reach that present appropriate operating options for each particular situation

  61. Leonardo Paskiewicz

    Hello there! Quick question that’s entirely off topic. Do you know how to make your site mobile friendly? My website looks weird when viewing from my iphone. I’m trying to find a theme or plugin that might be able to resolve this problem. If you have any recommendations, please share. Cheers!

  62. hypoallergenic dogs

    When I initially commented I clicked the «Notify me when new comments are added» checkbox and now each time a comment is added I get several emailswith the same comment. Is there any way you can remove me from that service?Thank you!

  63. Dwain Forlivio

    Undeniably believe that which you stated. Your favorite justification seemed to be on the net the easiest thing to be aware of. I say to you, I definitely get irked while people think about worries that they just do not know about. You managed to hit the nail upon the top as well as defined out the whole thing without having side effect , people can take a signal. Will likely be back to get more. Thanks

  64. klik untuk info

    The very next time I read a blog, I hope that it won’t fail me as much as this one. I mean, I know it was my choice to read through, nonetheless I actually thought you would have something useful to talk about. All I hear is a bunch of crying about something you could possibly fix if you weren’t too busy looking for attention.