A programming & designing blog!

Monday, December 23, 2013

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') ) {
		ob_end_clean();

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

		@fclose($fp);
		exit;
	}
}

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.


Usages

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

43 comments:

  1. Nice script! Thanks!

    ReplyDelete
    Replies


    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
      http://nhatroso.com/
      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
      http://we-cooking.com/
      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.

      Delete
  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

    ReplyDelete
    Replies
    1. I have read your blog its very attractive and impressive. I like it your blog.

      Digital Marketing Company in Chennai Digital Marketing Agency

      Delete

  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

    ReplyDelete

  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

    ReplyDelete
  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

    ReplyDelete

  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

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

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

    ReplyDelete
  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

    ReplyDelete
  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 CITIBANK OFFER,FLIPKART ICICI OFFER,
    SBI CARD OFFERS ON FLIPKART,
    FLIPKART CASHBACK OFFER TODAY,FLIPKART CREDIT CARD OFFERS,
    ALL BANK CREDIT CARD OFFERS,HDFC CREDIT CARD OFFERS ON FLIPKART,
    AXIS BANK CREDIT CARD OFFERS ON FLIPKART,
    CITIBANK CREDIT CARD OFFERS ON FLIPKART,SBI FLIPKART 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

    ReplyDelete

  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

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

    ReplyDelete
  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

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

    ReplyDelete
  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

    ReplyDelete
  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

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

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


    ReplyDelete
  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

    ReplyDelete
  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

    ReplyDelete
  21. There are many interesting information here.

    Sadie

    ReplyDelete