Labels

php (34) javascript (30) phpjavascript (29) jquery (23) html (19) mysql (14) database (9) codeigniter (4) json (4) bar chart (2) calendar (2) column chart (2) framework (2) google maps (2) query (2) tables (2) url (2) dropdown (1)

Sunday, March 11, 2018

How to force downloading a file using PHP.

Here we are providing a simple code of explaining how to make a user to download file forcefully.

Normally, you don't necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will automatically downloads that file. 

<a href="demo.jpg">Download</a>

Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip and exe files are downloaded automatically to the hard drive by default.

download.php
<?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 file selected";  
       }
}

index.php
<?php
include('download.php');
$file = 'demo.jpg'; 
force_download($file);
?>


HTTP header fields

The Content-Length entity-header field indicates the size of the entity-body,
in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD
method, the size of the entity-body that would have been sent had the request
been a GET. 

The text/html content type is an Internet Media Type as well as a MIME content type. Using HTML in MIME messages allows the full richness of Web pages to be available in e-mail. text/plain[RFC1521] The text/plain content type is the generic subtype for plain text.

In a regular HTTP response, the Content-Disposition response header is a header indicating if the content is expected to be displayed inline in the browser, that is, as a Web page or as part of a Web page, or as an attachment, that is downloaded and saved locally.


List of HTTP header fields
https://en.wikipedia.org/wiki/List_of_HTTP_header_fields

Similarly, you can force download other files formats like word doc, pdf files, etc.

134 comments:

  1. We have update list of do-follow blog commenting sites for new visitors, we will update this list regular basis so share our list to your friends also.
    the bookmarking sites

    ReplyDelete
  2. Nice article keep posting like this article

    ReplyDelete
    Replies

    1. We are putting all our efforts towards providing the best knowledge which will helpful to coding lovers.keep in touch with us regularly.

      Delete
  3. very good article....I am using PHP nOW

    ReplyDelete
  4. Download 4Liker APK for Androi devices such as Smartphone or Tablet to get Facebook and Instagram auto likes on the posts you shared and increase the likes on your posts. instagram 4liker

    ReplyDelete
  5. Good job
    KEEP IT UP
    Great job
    http://www-mcafee-activate.com/

    ReplyDelete
  6. Collection of modern office furniture in Melbourne. Adept Office supplies extensive range of office furniture in Melbourne. We also sell quality home computer furniture.

    ReplyDelete
  7. Smart cards or HID access cards are plastic identity card exactly like the dimensions of the driver’s license or credit card. The depth of a HID entry card may fluctuate based. Hid Access Card Copying

    ReplyDelete
  8. thank you, this is exactly what I was looking for! Very helpful <3
    Keep up the good work!

    ReplyDelete
    Replies

    1. We are putting all our efforts towards providing the best knowledge which will helpful to coding lovers.keep in touch with us regularly.

      Delete
  9. I am also associated with Goliath Cranes Manufacturers, EOT Cranes Manufacturers, by Pioneer Cranes is a leading Overhead Crane Manufacturers in India, and love to enjoy the stuff on the same as its rarely found on internet. Thanks again for writing such a good post.

    ReplyDelete
  10. I am also associated with E Rickshaw Dealers, E Rickshaw Dealers, by Erickshaw Dealers is a leading E Rickshaw Dealers in India, and love to enjoy the stuff on the same as its rarely found on internet. Thanks again for writing such a good post.

    ReplyDelete




  11. Alternative Aptoide App Stores are what have been most common these days. Gone are the days we depended upon the official app stores for our requirements of apps and games. aptoide ios

    ReplyDelete
  12. I would like to read again your next write-ups.
    It was so nice article.
    Thanks for Sharing.
    Long term airport parking at jfk

    ReplyDelete
    Replies

    1. We are putting all our efforts towards providing the best knowledge which will helpful to coding lovers.keep in touch with us regularly.

      Delete
  13. I am also associated with Fog Cannon Dust Suppression System, Industrial Humidification manufacturers in India, Outdoor Cooling System solution, Humidification for Tea Industries, and love to enjoy the stuff on the same as its rarely found on internet. Thanks again for writing such a good post.

    ReplyDelete
  14. Appreciate you sharing, great article post.Much thanks again.

    ReplyDelete
  15. Hmm This Is Very Nice and Awesome Stuff For Reading - Thanks For Sharing It Must Check This Indian Movies 2018

    ReplyDelete
  16. Writing on Php topic is always difficult but you did awesome work. Thank you for providing such amazing stuff.
    Source:
    Apple Support
    iTunes Tech Support
    MAC Tech Support
    icloud customer service

    ReplyDelete
  17. Great to see your article dear. thanks for sharing
    .

    ReplyDelete
    Replies

    1. We are putting all our efforts towards providing the best knowledge which will helpful to coding lovers.keep in touch with us regularly.

      Delete
  18. Good job Mr blog admin...it's a very use full information..

    ReplyDelete
  19. Great Post!!! Thanks for sharing.
    Have you just started learning and playing the game of Cricket Balls? Are you looking to buy your first Cricket Leather Ball? If yes, then Cricket Ball is the best choice for you. It’s all available at just a click: Cricket Balls || Cricket Leather Balls || international cricket ball price || sg cricket ball || cricket leather balls online

    ReplyDelete
  20. thanks you for this awesome post.

    must visit out website for latest bollywood news

    ReplyDelete
  21. best use full information thanks more goo.gl/uWCEew

    ReplyDelete
  22. Thanks, that's extremely good information, cheers.
    php development Melbourne

    ReplyDelete
  23. We offer you the best airport taxi service in Vienna. We are available 24 hours a day at +43 676 373 28 03. Order online today or call us and let us convince you of our service. VIP Airport Taxi - VIP Flughafentaxi http://flughafentaxi-vip-airporttaxi.at/

    flughafentaxi wien, flughafen taxi wien, airport taxi vienna, airporttaxi vienna

    ReplyDelete
  24. Really a great addition. I have read this post. Thanks for sharing information about it. I really like that. Thanks

    online assignment help

    ReplyDelete

  25. Your post is very unique and reliable information for all readers so write more on same topic and share with us your info. Thanks


    ReplyDelete
  26. really helpful info about php i want to thankful to you such a nice info keep sharing.mishtifnb

    ReplyDelete
  27. thanx.....https://seosmoservicebangalore.blogspot.in/

    ReplyDelete
  28. Breaking news of Technology,Business,Education,Gaming,Lifestyle, Is the best informative article sites News Entertainment, Business Finance news, Lifestyle Articles you check here latest news .

    ReplyDelete
  29. Truly community and free Dubai classifieds ad's website. Providing Dubai jobs, flats, villas, and rooms for rent, used cars, furniture. Buy, sell or find anything in Dubai for free.



    free classifieds in dubai

    ReplyDelete
  30. Here you can find all Government Jobs in Pakistan form different Government Departments.
    Government Jobs

    ReplyDelete

  31. Gbolamedia is a blog for entrepreneurs and small-business owners. Catch up the full insight about starting and running a successful business on Head in Here Now!
    Gbolamedia

    ReplyDelete
  32. Thank you for sharing information.It was very useful.
    Well done

    ReplyDelete
  33. Your selection of topic is very good and also well written. Thanks for sharing. I feel like all your ideas are incredible! Great job!!!
    travel-coupons

    ReplyDelete
  34. What is a Keylogger and how to use it? KeyGrabber keylogger is an undetectable keylogger, used for recording keystrokes on PS/2 and USB keyboards.

    ReplyDelete
  35. They're produced by the very best degree developers who will be distinguished for your polo dress creating. You'll find polo Ron Lauren inside exclusive array which include particular classes for men, women. hindi news

    ReplyDelete
  36. Every body check the buzztum website and get the Unique Information For All Generation please visit Buzztum

    ReplyDelete
  37. Your post inormation is very unique and useful for visitors Paypal Account

    ReplyDelete
  38. You have very strong information about latest topic i am really impress with you but you must improve your samrush and DA after posting more unique post like you have done so please use our DA Checker site.

    ReplyDelete
  39. Great article indeed. very helpfull. will surely recomend this to myfriends


    Planning to Buy App Reviews ? and Buy App Reviews Andrid . and boost up your plastore ranking?
    we can help you .

    ReplyDelete
  40. Hi! This is my first visit to your blog! I found your article very awesome thanks for sharing these information.You have very strong information about latest topic.
    You have given such a great information that will be very useful for me. I want to know more information deeply about it.
    Great Information
    Check this

    ReplyDelete
  41. Thanks you,
    You have given great information article that will be very useful for me. I want to know more information deeply about it.

    ReplyDelete
  42. digital marketing support the seo framework..

    ReplyDelete
  43. Thanks for sharing valuable content; this is what I need to know. Thank you once again, it's very interesting. I wish you all the best for your next blog in future...
    http://tmcelectronics.co.in/

    ReplyDelete
  44. This content is very helpful for me. Thanks for kind your information.

    ReplyDelete
  45. I've been looking for info on this topic for a while. I'm happy this one is so great. Keep up the excellent work 

    ReplyDelete

  46. Your selection of topic is very good and also well written. Thanks for sharing. I feel like all your ideas are incredible! Great job!!!
    firstcry-coupons

    ReplyDelete
  47. Thank's. https://rcfitnesswear.com/product-category/weightlifting-gear/grips/palm-protector/

    ReplyDelete
  48. I was just browsing along and just came upon your blog. Just wanted to say that this is an amazing blog and it's really helpful. All the best and keep it up. super p force online
    kamagra online
    kamagra polo online
    generic priligy online

    ReplyDelete
  49. Interesting stuff to read. Keep it up.
    quick attestation services is a very old name in the field of embassy document attestation services. We offer services like…
    document attestation services
    uae embassy attestation services
    certificate attestation for Kuwait
    qatar embassy attestation
    degree certificate attestation for Qatar and many more
    Please Visit on link below
    Website -> http://www.quickattestationservices.com/
    Facebook -> https://www.facebook.com/qas.attestation
    Facebook Page -> https://www.facebook.com/QuickAServices/
    Facebook Group -> https://www.facebook.com/groups/220497138530592/
    Twitter -> https://twitter.com/QuickAServices
    Google+ -> https://plus.google.com/u/0/114942161254844124346

    ReplyDelete
  50. It was wondering if I could use this write-up on my other website, I will link it back to your website though. Great Thanks.
    Oakville Dentist

    ReplyDelete
  51. Positive site, where did u up with information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include.
    edmonton dentist
    dental clinic edmonton

    ReplyDelete
  52. Nice Post.Thanks For Sharing With Us.

    ReplyDelete
  53. Hi, Thanks for you blog really informative, keeping post article like this
    ecommerce website design in london

    ReplyDelete
  54. This is really awesome post. I like this topic and also I like the way you have written this post. This site has lots of advantage.I found so many interesting things from this site. It helps me in many ways. Thank you so much for sharing such an amazing post. matrimonial Investigator is one of the leading Detective agency in Delhi, India. We provide you all needs of personal and corporate investigations services in all of India at very lowest cost.
    You can find here ...Best

    ReplyDelete
  55. Established in 1982, June Florist Pte Ltd is recognized as a pioneer in Singapore’s floristry industry. We are specialists in large scale floral arrangements for special events without focus on wedding, decorations for conferences. June Florist largest Same day flower delivery Singapore shop in Singapore.

    hand bouquet singapore
    flower delivery singapore
    hand bouquet
    online flower delivery singapore
    hand bouquet delivery singapore
    florist singapore
    flower in a box singapore
    bouquet delivery singapore
    flower bouquet delivery singapore
    flowers online singapore
    mother's day singapore
    Same day flower delivery singapore

    ReplyDelete
  56. THanku so much so provieding information about these topics
    more info https://goo.gl/Ci3hHk

    ReplyDelete
  57. Great article. I used to be checking out consistently this specific website exactly what prompted! Useful info especially the remaining portion :)Led High Bay

    ReplyDelete
  58. Indigo Industrial Supplies Ltd - UK Suppliers of Corex, Correx, Floor Protection, Carpet Protection and Industrial Consumables Home page. Indigo are UK suppliers of Corex, Correx, Temporary Floor Protection, Carpet Protection Film, Double Sided Tapes, Anti Slip Tape, Reflective Tape, Neodymium Magnets, Magnetic Tape, Magnetic Labels, Magnetic Sheet, Hook and Loop Tape Fastener, Packaging Supplies, Pallet Wrap, Stretch Film, Polythene Sheeting, Swann Morton Scalpel Blades



    temporary floor covering

    ReplyDelete
  59. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people.
    http://taazatadka.com/

    ReplyDelete
  60. I'm happy I discovered this site, I couldn't discover any learning on this matter earlier to.Also work a webpage and in the event that you are ever inspired by doing some guest composing for me if conceivable don't hesitate to tell me, im dependably search for individuals to look at my site.

    Fashion Blog Name Ideas

    ReplyDelete
  61. Interesting topic for a blog. I have been searching the Internet for fun and came upon your website. Fabulous post. Hotel in Dharamshala

    ReplyDelete
  62. The blog is absolutely fantastic. Lots of great information and inspiration, both of which we all need. Thanks for such a continuous great postings. . The blog is absolutely fantastic. Lots of great information and inspiration, both of which we all need. Thanks for such a continuous great postings.Detective Agency in Delhi

    ReplyDelete
  63. Thank you so much for sharing these amazing tips. I must say you are an incredible writer, i love the way that you describe the things.
    Hotel in dalhousie

    ReplyDelete
  64. This comment has been removed by the author.

    ReplyDelete
  65. Great article, Great content with all the helpful information.
    Visit 3D Animation Studio!

    ReplyDelete
  66. Happy to see your blog as it is just what I’ve looking for. I am looking forward to another great blog from you. Detective Agency in Delhi

    ReplyDelete
  67. Very useful information about PHP java .. Thanks for sharing such a useful content. i also share some important information- If any students searching Mathematics Tuition Center . click- http://www.pandeyacademy.org/

    ReplyDelete
  68. Established in 1982, June Florist Pte Ltd is recognized as a pioneer in Singapore’s floristry industry. We are specialists in large scale floral arrangements for special events without focus on wedding, decorations for conferences. June Florist is largest Same day flower delivery Singapore shop in Singapore.
    Hand bouquets make an ideal all-occasion gift, whether it is for a birthday, anniversary, graduation or just to show that someone special that you care.


    same day bouquet delivery
    floral bouquet singapore

    ReplyDelete
  69. I found so many interesting stuff in your blog especially its discussion. From the tons of comments on your blog, I guess I am not the only one having all the enjoyment here! keep up the good work.Detective Agency in Delhi

    ReplyDelete
  70. Excellent Blog. I really want to admire the quality of this post. I like the way of your presentation of ideas, views and valuable content. No doubt you are doing great work. I'll be waiting for your next post. Thanks .Keep it up! Import Export Code in Delhi

    ReplyDelete
  71. I have been looking for a rare blog because I am tired of accessing almost the same topic discussed in a website. This blog is actually hitting what I want to expect. I am very glad that you are now providing the information where I am hunting for many days of surfing the net.Detective Agency in delhi

    ReplyDelete
  72. PAK Communications


    PAK Communications has grown into a global, value-added security, surveillance and communication solutions provider to business and home consumers. Our solutions include various ranges of Security Cameras Systems, PABX Systems, Fire Alarm Systems, Intercom Systems, Access Control Systems, Time Attendance Systems, Network Cabling and Configuration.


    CCTV Karachi

    CCTV Camera Karachi

    PABX Karachi

    PBX System in Karachi

    ReplyDelete
  73. Finmortg Brokers
    Our expert mortgage and finance brokers find and help you in getting your suitable home loan, car loan and business loan. Refinance Mortgage, Mortgage Calculator, Mortgage House



    Mortgage calculator

    Refinance mortgage

    Mortgage House

    ReplyDelete
  74. M Super Hosting



    We present Word Press base web design services generally apply personal custom and paid themes on buyer order. Our web design and web development apparatus involve CMS particularly Word Press, Magneto and open-cart, Web Hosting we usually upload websites on our own fast and trustworthy web servers and register domains as per customer need Web Hosting Karachi.


    Web Hosting in Karachi

    Software House in Karachi

    Web Hosting

    SEO Karachi

    SEO Company

    SEO Services

    Search Engine Optimization

    SMS marketing

    SMS Marketing in Karachi

    SMS Marketing Pakistan

    Logo Design in Karachi

    Graphic Design in Karachi

    ReplyDelete
  75. Thanks very nice share ... I follow your site constantly ... important issues ... Congratulations ... I entered this site by chance, but I found very interesting.Detective Agency in Delhi

    ReplyDelete
  76. nice post

    https://onlineweblogsite.blogspot.in/

    ReplyDelete
  77. It's always a good idea to set your SEO Keywords, Descriptions, and page titles. These are key terms that search engines use to rank & find your site. In Duda, there are two places to set SEO keywords: Page Settings & Site settings. These are for page specific SEO terms & global site SEO terms, respectively. Here is an example of how to set the keywords, descriptions, and titles for your site.

    SEO Made Simple: A Step-by-Step Guide

    ReplyDelete
  78. Zayn Malik Wiki |Modelling Career | Biography | Height | Weight | Age | Awards | Girlfriend | Wife | Affair | Controversies | Family | Life Story

    ReplyDelete
  79. Happy to see your blog as it is just what I’ve looking for. I am looking forward to another great blog from you. Detective Agency in Delhi

    ReplyDelete
  80. Effective efforts taken for php users, my developer will really found a real big smile. Thanks for sharing. petrochemical forging components India

    ReplyDelete

  81. how to write a successful blog Learn how to build a profitable business online by mastering SEO, affiliate marketing and take your blog to the next level.

    ReplyDelete


  82. Toronto's entrepreneur

    TorontoStarts is Toronto's Entrepreneur & Toronto Startup community network. Leading the Innovation revolution with programs designed to accelerate the start up process & by connecting entrepreneurs, innovators, visionaries, hustlers, disruptors, hackers, investors & incurable risk-takers!

    ReplyDelete
  83. I am impressed. This is a fantastic blog. You obviously know what your subject matter! I studied it with great interest and look forward to the next updates. I have grabbed the rises feed to stay up to date of any further updates. Detective Agency in Delhi

    ReplyDelete
  84. June Florist - Same day flower delivery singapore. Call June Florist for floral arrangements for wedding, decorations for conferences, hand banquet decorations, Flower Box, table flower arrangement & more. Tel: +65 6282 7555
    flower bouquet online delivery
    order bouquet online singapore

    ReplyDelete
  85. Hello I am so delighted I found your blog, I really found you by mistake, while I was looking on Yahoo for something else, anyways I am here now and would just like to say thanks for a tremendous post. Please do keep up the great work. Matrimonial Detective Agency in Mumbai

    ReplyDelete
  86. I personally feel your website topic is very unique and reliable for readers. We are waiting new more informative articles for increasing knowledge threat synonym .

    ReplyDelete
  87. It is actually a great and helpful piece of information. I am satisfied that you simply shared this helpful information with us. Please stay us informed like this. Thanks for sharing. Guest Posting Sites List 2018

    ReplyDelete
  88. This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It is the old what goes around comes around routine.

    Free online advertising platforms

    ReplyDelete
  89. I truly delighted in perusing this post, enormous fan. Keep doing awesome me when would you be able to distribute more articles or where would I be able to peruse more on the subject?
    desktop pc sale

    ReplyDelete
  90. https://www.codeavail.com/UML-Diagram-Help
    UML Diagram Help
    CodeAvail provides Homework Help in UML Diagram, Class Diagram, UML Modeling and Sequence Diagram. Get UML assignment help from professional tutors of codeavail.com. The 24/7 online UML assignment writing service will allow you to gain a technically accurate assignment. UML Assignment Experts are offering UML Assignment Help Online. We offer the best UML Diagrams Assignment Help/ UML Diagrams Homework Help/ Project Help to students of Australia, US and UK Submit your UML Assignment for Help Now! CodeAvail- Online Computer Science Assignment help
    https://www.codeavail.com/SubmitWork

    ReplyDelete
  91. I am impressed. This is a fantastic blog. You obviously know what your subject matter! I studied it with great interest and look forward to the next updates. I have grabbed the rises feed to stay up to date of any further updates. Digital Signature in Delhi

    ReplyDelete
  92. General charges for house moving administrations will incorporate different charges, for example, Charges and cost of pressing materials Wellbeing of your products while travel is extremely significance, would it say it isn't? I am certain you might not want to trade off with security of your significant family merchandise. So how employing a http://indiaedge.in/packers-and-movers/gurgaon will has a major effect? The legitimately pressing with great material with great layers is such an packer and movers bangalore thing in this way, to the point that it won't get harmed effectively while travel. Presently there are distinctive – diverse sort of pressing material and there is a standard of pressing. So next time when you manage a packers and movers, ensure what they will use for the wellbeing of your products, similar to froth, cardboard, wooden case and so on. It's undeniable better quality pressing material will packer and movers noida cost all the more then shoddy quality toons and pressing materials.

    ReplyDelete
  93. you will face many problems in your computer and laptop with the entire functioning. So, it is a must to take proper care of windows to keep it functioning for long time and use best service Time to time running http://getphonehelp.com/norton-antivirus-support/ on your windows system is a must. http://getphonehelp.com/outlook-customer-support/ if you needlittle help to your printer of your HP products. find live and phone support for hp visit our site you will get direct contact for hp http://getphonehelp.com/hp-printer-support/

    ReplyDelete
  94. Your blog is Very likely I’m going to bookmark your blog also. Its really helpful for me and many others. You absolutely have wonderful stories. Thanks for sharing with us Enjoyed every bit of your blog.

    ReplyDelete
  95. https://www.codeavail.com/Artificial-Intelligence-Homework-Help
    Artificial Intelligence Homework Help
    If you are worried about your grades in Artificial Intelligence Assignment, then take help from our assignment writers at codeavail.com and get assured of scoring high in the final results. Our Artificial Intelligence assignment help is primarily designed to help you out with the assignment writing task where all your academic requirements will be taken care of. Get Best Artificial assignment & homework help at an affordable price. Get Help Now! CodeAvail- Online Computer Science Assignment help
    https://www.codeavail.com/SubmitWork

    ReplyDelete
  96. nice....

    #simba#simbainfotech
    http://www.simbainfotech.com/
    http://www.simbainfotech.com/
    http://www.simbainfotech.com/
    http://www.simbainfotech.com/

    ReplyDelete

More Posts

FOLLOW