Skip to main content

Force File Download with PHP

If you want to control or track your downloadable contents then a force file downloader script can give you more option. Especially if you want make images or other stemming contents like music file (mp3, wav, ogg), video files (flv, mp4, ogg, 3gpp), css, JavaScripts or even a php file downloadable then you must need to use a force file downloader script.

In this post I am going to share a simple but useful force file downloader script.

Download Source

The Download Function

 * force file to download
 * @param string path to file
function download($path)
	// if file is not readable or not exists
	if (!is_readable($path))
		die('File does not exist or it is not readable!');

	// get file's pathinfo
	$pathinfo = pathinfo($path);
	// set file name
	$file_name = $pathinfo['basename'];

	// guess mime type by extension
	$mimes = require 'mimes.php';
	$mime = isset($mimes[$pathinfo['extension']]) ? $mimes[$ext] : 'application/octet-stream';

	// set headers
	header('Pragma: public');
	header('Expires: -1');
	header('Cache-Control: public, must-revalidate, post-check=0, pre-check=0');
	header('Content-Transfer-Encoding: binary');
	header("Content-Disposition: attachment; filename=\"$file_name\"");
	header('Content-Length: ' . filesize($path));
	header("Content-Type: $mime");

	// read file as chunk to reduce memory usages
	if ( $fp = fopen($path, 'rb') ) {

		while( !feof($fp) and (connection_status()==0) ) {
			print(fread($fp, 8192));


Heavy memory usages is one of the most common issue of almost all force file downloader script. That's why I am not using functions like readfile. Because these files first stores whole file to the memory and then it starts download. If you want to try large files to download using this function then you will get memory limit exhausted problem. So, it is better to read a file as chunks.


$file = $_GET['file'];
download('path/'. $file);


  1. Nice script! Thanks!


    1. Địa Ma Lão Nhân ngưng thân hình một lát phát hiện trước mặt không có người nào đuổi theo còn tưởng rằng có thể đào thoát ai ngờ mình dính phải một bình chướng vô hình ngăn cản.

      - Ngươi đừng hòng chạy thoát.

      Nhạc Thành đã xuất hiện sau lưng của Địa Ma Lão Nhân, ba vòng sáng xuất hiện xoay vòng.

      Ám Ảnh Kiếm đã sớm hiện ra trong tay của Nhạc Thành, ba luồng sáng mang theo lực lượng cường hãn mà phóng tới, Địa Ma Lão Nhân không có thân thể Kim Long như Nhạc Hạo, không có tốc độ như Trần Tân chỉ dongtam
      mu moi ra hom nay
      tim phong tro
      nhạc sàn
      tổng đài tư vấn luật
      văn phòng luật hà nội
      tổng đài tư vấn luật
      thành lập công ty trọn gói
      chém gió
      trung tâm tiếng anhcó thể lui lại vài phần.

      Đúng lúc Địa Ma Lão Nhân lui lại thì một hắc mang rất lớn gào thét, ở giữa không trung hoá thành cự trảo đen kịt, chộp tới ba Ám Ảnh Kiếm.

      - Phá cho ta.

      Thủ ấn của Nhạc Thành một lần nữa biến đổi, Âm Dương Kiếm ở giữa không trung hơi tản ra, lập tức biến thành một phương hướng không thể xác định được ngăn cản trước cự trảo.

  2. Wow amazing i saw the article with execution models you had posted. It was such informative. Really its a wonderful article. Thank you for sharing and please keep update like this type of article because i want to learn more relevant to this topic.

    Web Designing Training in Chennai


  3. Helpful as always. Every post you write produce a massive value to your readers that is the only reason it is so popular and has great authority. I read this content really awesome.I hope this information may change my business carrier.I can remember these things whenever taking the decision.

    SAP training in Chennai


  4. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

    SAP training in Chennai

  5. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us.

    SAP training in Chennai


  6. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

    Digital Marketing Training in Chennai

  7. Really thanks for sharing your valuable information, it is really useful to help and understand.
    PHP Training in chennai

  8. You have shared very informative news with. Thanks for your effort.php training classes

  9. lipkart is Offering Cashback Offers Flipkart hdfc cashback offers You will get upto 75% Discount

    Flipkart is Offering Cashback Offers Flipkart SBI Cashback Offer You will get upto 75% Discount

    Flipkart is Offering Cashback Offers Flipkart AXIS Cashback Offer You will get upto 75% Discount

    Flipkart is Offering Cashback Offers Flipkart YES Cashback Offer You will get upto 75% Discount

    Flipkart is one of the biggest world wide eCommerce Site so here you will getFlipkart big billion day offers

    Flipkart is one of the biggest world wide eCommerce Site so here you will getflipkart bank cashback offersso

  10. nice post.super article .iam follow your website.

    Flipkart CashBack Offers-SBI, HDFC, ICICI, Citibank Cards&Flipkart HDFC Cards Offers"
    flipkart bank offers,flipkart cash back coupons,flipkart offers 2018,flipkart coupons 2018,flipkart cashback offers 2018,flipkart cashback offers,flipkart cash back offers,flipkart cashback coupons,flipkart cashback,Flipkart Cashback Offers,Flipkart Bank Offers,Flipkart Deals 2018, flipkart upcoming offers on mobiles, hdfc credit card offers on flipkart 2018 flipkart sbi offer big billion day, flipkart hdfc offer, flipkart hdfc offer august 2018 sbi flipkart offer 2018 flipkart icici offer


    Flipkart Cashback Offers||Flipkart Bank Offers||Flipkart Deals 2018||flipkart upcoming offers,"
    "Flipkart Cashback Offers || Flipkart Bank Offers || Flipkart Deals 2018 ||" "flipkart upcoming offers on mobiles, hdfc credit card offers on flipkart 2018, sbi credit card offers on flipkart today, flipkart hdfc offer terms and conditions, sbi flipkart offer 2018, flipkart cashback phonepe, flipkart hdfc offer august 2018, flipkart icici offer

    "cashback,vouchers,coupons,discounts,offers,deals,promo codes,&Cashback Offers"
    "cash back coupons "Coupons, Discounts & Offers on 1500+ Shopping Sites in India. Get Extra Cashback Everytime You Shop Online using Coupons of Amazon, Flipkart, Tata CLiQ, Nykaa etc."cashback, vouchers, coupons, discounts, offers, deals, promo codes,Coupons, Promo Codes & Cashback Offers


  11. Offersable - Cash Back Offers | Discount Coupons | Bank Offers | Promo Codes.
    Find best Discount Coupons, Cashback Offers, Hot Deals Bank Offers for all major e-commerce stores in the India

    Amazon cashback offers 2018Cashback Deals with sbi,hdfc,icici,axis banks,credit&debit card,
    Amazon Cashback Offers 2018 Upto 65% Cashback Deals, AMAZON CASHBACK OFFERS 2018, DISCOUNT COUPON OFFERS 2018, Amazon cashback offers with sbi hdfc icici axis banks credit&debit card offers more. amazon cashback offers2018,amazon india cashback,amazon offers on mobiles,amazon cashback2018,amazon offers 2018

    cashbackoffer amazon coupon code| amazon coupon promo code| amazon offer coupon code|
    amazon coupon code| amazon coupon promo code| amazon offer coupon code

    About Airport Parking,Accor HotelsAffordable Asia,Agoda,Air Asia Go,Akbar Travels,Amoma,Azores Getaways,Big Bus Tours,Booking,CarmelLimo,CatchThatBus,CheapAir,CheapTickets Singapore,Cleartrip,Ctrip English speaking,Etihad Airways,Expedia,Expedia India, Expedia Indonesia Hotels, Flights & Packages,Travel Coupons, Offers: Flights, Hotels, Bus Promo Codes

    CashBack Offers, Discount Coupons, Bank Offers & Promo Codes

    flipkart cashback offer,
    CashBack Offers, Discount Coupons

    Pepperfry, Mobikwik, Firstcry, Fab Hotels, Ebay, Aliexpress, Adidas, Healthkart, Pepperfry, Shoppers Stop, FlipKart, Amazon, Lurap, Giftalove, Reebok, SBI Card, CoolWinks, Housejoy, Shine, Jaypore, netmeds, FabAlley, Prettysecrets, FlowerAura, Clovia, Shopclues, Printvenue, Firstcry, Travelguru, Myntra, Zivame, Jabong, Ferns N Petals,Healthkart, Pepperfry, Shoppers Stop, FlipKart, Amazon

    CashBack Offers, Discount Coupons, Bank Offers & Promo Codes

    CashBack Offers, Discount Coupons, Bank Offers & Promo Codes

    CashBack Offers, Discount Coupons, Bank Offers & Promo Codes

  12. I also encounter the same problem. thanks for your answer. It solved very quickly the problem I was having hotmail sign in

  13. I strongly believe that there will be great opportunities for those who looked into this area...
    Best Online Software Training Institute | Real-Time Project on PHP

  14. I hope this information may change my business carrier. moto x3m, slope, short life

  15. This is really a nice and informative, containing all information and also has a great impact on the new technology.
    SEO Training Chennai
    SEO Placement

  16. Learned a lot of new things from your post! Good creation and HATS OFF to the creativity of your mind. Very interesting and useful blog!
    Python Training in Chennai
    Python Course in Chennai

  17. I was barely amazed at how you had written this content. Please keep posting.
    Best PHP training in chennai
    PHP Training

  18. شركة مجموعة زهور العاصمة أفضل شركة على مستوى المملكة العربية السعودية والدمام بشكل خاص تقوم بكافة الخدمات المنزلية على أعلى مستوى وبأرخص الأسعار عليك التواصل مع الشركة الرائدة في مجال كشف تسربات المياة وعزل الأسطح والتنظيف ومكافحة الحشرات عبر الرابط التالي
    شركة كشف تسربات المياه بالدمام
    شركة عزل أسطح بالدمام
    شركة تسليك مجاري بالدمام
    شركة ترميم منازل بالدمام

  19. Wonderful Blog on recent updates, I have updated my knowledge through your blog, Thanks admin for sharing the recent information.
    iOS Training in Chennai
    iOS Training Institutes in Chennai

  20. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.

    Digital Marketing Course in Chennai
    Digital Marketing Training in Chennai
    Online Digital Marketing Training
    SEO Training in Chennai

  21. There are many interesting information here.


  22. Thanks For Sharing This Blog Very Useful Content And More Informative

    Microservices Online Training

  23. Hi Thanks for the nice information its very useful to read your blog.
    Advanced SEO Training

  24. Good job in presenting the correct content with the clear explanation. The content looks real with valid information. Good Work

    DevOps is currently a popular model currently organizations all over the world moving towards to it. Your post gave a clear idea about knowing the DevOps model and its importance.

    Good to learn about DevOps at this time.

    devops training in chennai | devops training in chennai with placement | devops training in chennai omr | devops training in velachery | devops training in chennai tambaram | devops institutes in chennai | devops certification in chennai | trending technologies list 2018

  25. I really like what you describe, good to know such things.
    DevOps Online Training


  26. Thanks for the Kind Information. This information is very much useful like You can allow me to post the upword Thank you again for posting this.

  27. This comment has been removed by the author.

  28. Thanks for the great information , i was looking for this information from long.Great blog
    tally course in hyderabad

  29. Best Business Analytics Training, Big Data Analytics And Data Scientist Course / Data Science Course Training In Hyderabad, With 100% Placement Assistance.

  30. I am so glad today fortune turned to face me and not the booty as usual there were financial difficulties and I decided to play online casino stumbled upon this site reliable online casino list how good it was that I found it


Post a Comment

Popular posts from this blog

Multiple File Upload with PHP

Sometimes we need to allow our users to upload multiple file upload. On my previous post I was shown the basic of simple file upload with PHP. Today I am going to show you how to allow users to upload multiple files. It is almost similar like simple file upload but we need to do some modification with html markup and php code. multiple attribute is needed to add on the html markup. Major web browsers like Firefox, Chrome, Safari and IE 9+ support this attribute. Now I am going to show you how to upload multiple file with PHP and basic HTML form.

Live Comment System with jQuery Ajax PHP and MySQL

Recently I have been made a post that focused on how to submit form without page refreshing. That post shows the basic functionality of using jQuery Ajax. On the same follow this post will describe how we can create a comment system to post an instant comment without page refreshing. Let's start...

Resize Image While Uploading with PHP

On my previous post I was shown an example how to upload file with php and html. It was based on php simple image upload functionality. Today I am going to show you little bit advance of image uploading. Suppose if you run a website and want to allow users to upload image files than you need to think little bit about server's space and bandwidth. For this purpose you need to do some optimization with image files. Image resize while uploading is one of them. All major website do it in the same way. If a user uploads a 5mb image file they resize it in different sizes and store on there server. It helps them to seed up there website and reduce there budget. Now take a look, how we can do it ourself.