fcOnTheWeb Logo Web technologies, made easy.

fcOnTheWeb Red DotForce download with PHP

Sometimes when you are linking to a file, you want the user to download that file rather than view it in their browser. This applies to file that they can view, such as images (JPEG, GIF, etc.), PDFs, MP3s, etc.

You need to force the user to download the file. We can do this with PHP quite easily. However, there are a few considerations to bear in mind, and we will address these shortly. First, let's see an example.

Below are four links to two files. The top link to each file opens it in the browser, in a new window. The second link to each file forces user to download the file.

So as you can see, one link shows the element in the browser as per normal, the second link forces the download option upon you. How is this done? Well, when we want to force the download we direct the user to a PHP page (in this case download.php) which then delivers the file to the user. Let's take a look at the code we need to put on download.php.

$filename = $_GET["file"];

$file_extension = strtolower(substr(strrchr($filename, "."), 1));

if ($filename == "") {

echo "<html><title>Download</title><body>No filename given.</body></html>";

exit();

} elseif (!file_exists($filename)) {

echo "<html><title>Download</title><body>File not found.</body></html>";

exit();

}

switch ($file_extension) {

case "pdf":

$contenttype = "application/pdf";

break;

case "jpg":

$contenttype = "image/jpg";

break;

}

header("Content-Type: " . $contenttype);

header("Content-Disposition: attachment; filename=\"" . basename($filename) . "\";");

readfile($filename);

exit();

Now, it is important to note that this is the minimum amount of code to get this procedure to reliablly work. We will look at extra code we can add shortly.

The first part of our code simply gets the filename we passed in through the URL, gets the file extenstion and then performs a couple of checks. We check that filename is present, and that the file does exist. If either of these checks fail, we display an error message on end the process.

If that is in order, we carry on. We set the content type based on the file extenstion, and then we deliver the file to the user before ending the process. It's quite simple when the code is cut down the minimum like this.

The URL we give the user is simple as well. Just download.php with file attached:

<a href="download.php?file=image.jpg">download.php?file=image.jpg</a>

And that's the basics of forcing the content to the users. Now we will look at some important issues with this method, and some more code to make things a little nicer.

The first major issue we run into with this procedure is security. Using this code will create a massive security flaw. The above code will download any file that is passed in through the URL. That means a villan could pass in a string such as "../../conn.php" and then download your raw database connection file. This will give them your database username and password. Any file can be downloaded this way. So what can we do?

There are more than a couple of options, but we will look at two easy ones. The first option is to only allow explicit files to be downloaded. A simple if statement checking the filename will suffice here. Something like:

if ($filename != "pdfdocument.pdf") {

exit();

}

This will cause the process to end if the filename passed in is not "pdfdocument.pdf". Of course, you might want to display and error message or something like that to inform the user.

Another method that could be used is to store the file names and/or locations in a database, then only pass through the ID number of the file to download. Based on this ID you could retrieve the correct path to the file. This way any file that is not in the database cannot be downloaded.

There are other methods of course which will work better and may be more complex. Applying a little bit of thought to the problem is bound to come up with a solution that works for you, but it is important to recognise this risk before implementing a system like this on your site.

Some other content types that can be used can be seen below. These can simply be added to the switch statement above.

case "exe":

$contenttype = "application/octet-stream";

break;

case "zip":

$contenttype = "application/zip";

break;

case "doc":

$contenttype = "application/msword";

break;

case "xls":

$contenttype = "application/vnd.ms-excel";

break;

case "ppt":

$contenttype = "application/vnd.ms-powerpoint";

break;

case "gif":

$contenttype = "image/gif";

break;

case "png":

$contenttype = "image/png";

break;

default:

$contenttype = "application/force-download";

There are also a few header parameters we can add in, such as:

header("Pragma: public");

header("Expires: 0");

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

header("CCache-Control: private", false);

header("Content-Transfer-Encoding: binary");

header("Content-Length: " . filesize($filename));

And that concludes our article. The technology is there, but use it wisely. Please. This method can be quite handy, but it is not without risk.

The code we have used at fcOnTheWeb, which we have then based this article off, can be found at http://elouai.com/force-download.php. We created our PDF document with PDF Online.

ferrari_chris

Lenny says:

2013-03-13 12:22:48

Hi Chris,

This script works except for the fact that when my "Save as" dialog box pops up in Firefox, the "Open With" option is ticked, not the "Save File" option.

I noticed that your "image.jpg (download)" example given prompts the "Save File" option.

I'm using a gif and made sure to change the content type to "case "gif": $contenttype = "image/gif";"

Is there a way to force the dialog box to prompt the "Save As" option for a gif instead of the "Open With" option?

Thanks.

__________

dave says:

2013-06-10 11:05:51

Hi, very helpful this!

Is it possible to have a
"if file-type == .jpg"
function or something along those lines
to fix the security risk?

Thanks

__________

Márton Bálint (http://www.szimbol.hu) says:

2013-09-20 22:02:14

Thank you for this stuff. It was very simple and useful.

__________

Cheap Ralph Lauren UK (http://cheapralphlaurenuk.1minutesite.co.uk/) says:

2014-01-18 03:07:15

Gucci Shoes UK, http://www.guccivshoesfactory.net/
Polo Ralph Lauren Outlet Online, http://www.rralphlaurenoutlet.com/
Ralph Lauren Outlet Online, http://www.ralphlaurenipolo.com/
Ralph Lauren UK, http://www.polo-outletstoreonline.com/
Beats by Dre, http://www.discountbeatsbydresale.com/
Sacs Longchamp Pairs, http://www.saclongchamppairs.com/
Canada Goose Outlet, http://www.thecanadagooseoutlet.com/
Hollister UK Shops, http://www.cheaphollistersale.co.uk/
Michael Kors Outlet Online, http://www.michaelkors.so/
Marc Jacobs Outlet, http://www.marcjacobsonsale.com/
Michael Kors Outlet, http://www.michaelkorsr.com/
North Jackets Clearance, http://www.north-faceoutletonlines.net/
Burberry Outlet Online, http://www.burbagssale2013.com/
North Clearance Outlet Online, http://www.north-clearance.com/
Coach Factory, http://www.coach-factories.com/
Coach Outlet Online, http://www.coach-purseonsale.com/
Cheap Ralph Lauren UK, http://cheapralphlaurenuk.1minutesite.co.uk/
http://marcjacobsoutlet-2014.tripod.com/
http://www.michaelkorsoutletr.com/
Michael Kors Outlet
Discount Michael Kors
http://www.michael-korsfactorystore.com/
Michael Kors Outlet
Michael Kors Factory Store
http://www.michaellkorsfactoryonline.com/
Michael Kors Outlet
Discount micheal kors

__________

mbt usa (http://www.speaiclbag.com) says:

2014-04-16 07:08:49

Now, since the quality is a general term, such as bags and the quality of the selection of the base material, with the hand, the work of Louis Vuitton bags http://www.speaiclbag.com are collected and mirror, finally, the strength of the bags.

__________

oakley sunglasses cheap (http://www.oakleysunglassescheap.us.com/) says:

2014-07-12 07:03:44

http://www.oakleysunglassescheap.us.com/ oakley sunglasses

cheap
http://www.coachoutletstoreonlineco.com/ coach factory outlet
http://www.abercrombie-andfitch.com/ abercrombie and fitch
http://www.michaelkors-outletsonline.com/ michael kors outlet
http://www.oakley-sunglassesoutlet.com/ oakley sunglasses

outlet
http://www.tory-burchoutlet.com/ tory burch outlet
http://www.abercrombieandfitchstore.com/ abercrombie & fitch
http://www.rayban--sunglasses.com/ ray ban sunglasses
http://www.fit-flops.co.uk/ fitflops
http://www.coachoutlet-factoryonline.com/ coach factory outlet
http://www.toryburch-shoes.com/ tory burch shoes
http://www.coachstoreonline.org/ coach outlet store online
http://www.coachfactory-outletinc.com/ coach factory outlet
http://www.cheapraybansunglasses.us/ cheap ray ban sunglasses
http://www.valentino.us.com/ valentino
http://www.fitfloponline.co.uk/ fitflop uk
http://www.coach-outletinc.com/ coach outlet
http://www.coachoutlet-factorystore.com/ coach outlet store

online
http://www.airjordan.us.com/ air jordan
http://www.timberlandshoesus.com/ timberland shoes
http://www.michaelkorsoutlet-online.us/ michael kors outlet
http://www.coachfactoryoutletnew.com/ coach factory outlet
http://www.coach-factoryoutletinc.com/ coach factory outlet
http://www.truereligionbrandjeans.us.com/ true religion outlet
http://www.truereligionjeans.us.com/ true religion jeans
http://www.coach--handbags.com/ coach outlet online
http://www.louisvuitton--outlet.us/ louis vuitton outlet
http://www.timberland--shoes.com/ timberland boots
http://www.isabelmarantshoes.us.com/ isabel marant shoes
http://www.coachoutletonline-factory.com/ coach outlet online
http://www.michaelkorsoutlet-online.net/ michael kors purses
http://www.louisvuitton-handbag.us/ louis vuitton handbags
http://www.coach-outletstoreonline.com/ coach outlet store

online
http://www.true-religion-jeans.com/ true religion jeans
http://www.coach-outletfactoryonline.com/ coach factory outlet

online
http://www.officialcoachfactoryoutlet.com/ coach factory outlet
http://www.louisvuitton-outlet.org/ louis vuitton outlet
http://www.coach-factoryoutlets.com/ coach factory outlet
http://www.coach-outletonline.us/ coach outlet online
http://www.michaelkorsoutletonlinestore.us/ michael kors outlet
http://www.michaelkorsoutletstoresco.com/ michael kors outlet

store
http://www.tiffanysjewelry-co.com/ tiffany and co jewelry
http://www.celineoutlet-online.com/ celine outlet
http://www.cheap-toms.net/ toms shoes
http://www.celine-handbags.com/ celine handbags
http://www.toms--shoes.us/ toms outlet
http://www.fitflopsandalssale.com/ fitflops
http://www.fitflopusaonline.com/ fitflop outlet
http://www.prada-handbag.com/ prada handbags
http://www.tiffanyandcoinc.com/ tiffany jewelry
http://www.prada-outlet.org/ prada outlet
http://www.michael-korsoutletinc.com/ michael kors
http://www.marcjacobs.us.com/ marc jacobs
http://www.supra.us.com/ supra shoes
http://www.ralphlauren.us.com/ polo ralph lauren
http://www.tiffanyjewelry.us.com/ tiffany jewelry
http://www.shoestoms.net/ toms shoes

__________

POLO says:

2014-08-04 07:45:06

http://www.superbagsmarket.com/ Super Bags Market
http://www.nike-jordanshoes.com/ Nike Jordan Shoes
http://www.thebeatsbydre.net/ Beats By Dre Outlet
http://www.michaelusakors.com/ Michael Kors Outlet Online
http://www.polo-tshirts.com/ Ralph Polo Outlet Online
http://www.northsclearance.com/ North Clearace Outlet
http://www.polo-ralphlaurenonline.com/ Ralph Polo Outlet
http://www.guccishoesuk-2014.net/ Gucci Shoes Outlet
http://www.michaelkorsstates.com/ Michael Kors Outlet
http://www.polooutlet-store.com/ Polo Outlet Store
http://www.ralph-laurenhome.com/ Ralph Lauren UK
http://www.marcjacobsonsale.com/ Marc Jacobs On Sale
http://www.mcmworldwides.com/ MCM Outlet
http://www.salongchamppairs.com/ Sac Longchamp Pairs
http://www.canada-gooser.com/ Canada Goose Outlet
http://www.burberrybags2014.com/ Burberry Outlet
http://www.michaelkors.so/ Michael Kors Outlet
http://www.oakley-sunglassfactory.com/ Oakley Sunglaases Factory
http://www.north-faceoutlet.us.com/ North Face Outlet Online
http://www.moncler-clearance.com/ Moncler Clearance
http://www.woolrich-clearance.com/ Woolrich Clearance
http://www.barbour-jacketsoutlet.com/ Barbour Jackets Outlet Online
http://www.moncler-jacketsoutletonline.com/ Moncler Jackets Outlet Online
http://www.monsterbeatsbydres.net/ Monster Beats Outlet
http://www.louis-vuittonblackfriday.com/ Louis Vuitton Outlet
http://www.lv-guccishoesfactory.com/ Louis Vuitton Factory
http://www.mcmoutlet-jp.com/ MCM 店铺
http://www.cheapdiscountoutlet.com/ Discount Clothes Sale
http://www.michael-korsfactoryonline.com/ Michael Kors Factory Online
http://www.coach-factoryoutlets.net/ Coach Factory Outlet
http://www.coach-blackfriday.net/ Coach Black Friday
http://www.coach-storeoutletonline.com/ Coach Store Outlet Online
http://www.coach-factoryoutletonlines.com/ Coach Factory Outlet Online
http://www.coachcoachoutlet.net/ Coach Outlet
http://www.coach-factory.net/ Coach Factory
http://www.coach-pursesoutlet.net/ Coach Purses Outlet Online
http://www.coach-outletonline.net/ Coach Outlet USA
http://www.mksfactoryoutlet.com/ Michael Kors Factory Outlet
http://www.zxcoachoutlet.com/ Coach Outlet Online USA
http://www.mischristmas.com/ Coach Factory Outlet Online
http://www.misblackfriday.com/ Black Friday
http://www.newoutletonlinemall.com/ Coach Purses Outlet Online
http://www.clickmichaelkors.com/ Michael Kors USA
http://www.cmichaelkorsoutlet.com/ Michael Kors Outlet USA
http://www.ralphlaurenepolo.com/ Ralph Lauren Polo

__________

hollister clothing store (http://www.rayban--sunglass.com/) says:

2014-08-05 07:22:37

http://www.rayban--sunglass.com/ ray ban sunglasses
http://www.customscopyright.com/ coach factory outlet
http://www.hollisterclothing-store.com/ hollister clothing store
http://www.michael--korsoutletonline.com/ michael kors outlet online
http://www.oakley--sunglass.com/ oakley sunglasses cheap
http://www.saclancelfrance.com/ sac lancel
http://www.katespade--outlet.com/ kate spade outlet
http://www.katespadeoutlet-online.com/ kate spade outlet online
http://www.katespade-online.com/ kate spade online
http://www.coachoutlet-onlinestore.com/ coach factory outlet
http://www.abercrombie-andfitch.com/ abercrombie and fitch
http://www.michaelkors-outletsonline.com/ michael kors outlet
http://www.sacportefeuille.com/ sac portefeuille
http://www.oakley-sunglassesoutlet.com/ oakley sunglasses outlet
http://www.michael--korsoutlet.com/ michael kors outlet
http://www.toryburch-outlet-online.com/ tory burch outlet online
http://www.abercrombieandfitchstore.com/ abercrombie & fitch
http://www.fit-flops.co.uk/ fitflops
http://www.coachoutlet-onlinefactory.com/ coach outlet online
http://www.coachfactoryoutlet-bag.com/ coach factory outlet
http://www.tory-burchshoes.com/ tory burch shoes
http://www.coachfactoryoutletclearance.com/ coach factory outlet
http://www.raybansunglasses-cheap.com/ cheap ray ban sunglasses
http://www.valentino.us.com/ valentino
http://www.fitfloponline.co.uk/ fitflop uk
http://www.coach-outletonlinefactory.com/ coach outlet
http://www.coachoutlet-factorystore.com/ coach outlet store online
http://www.air--jordans.com/ air jordan
http://www.timberlandshoesus.com/ timberland shoes
http://www.michaelkors--handbags.com/ michael kors handbags
http://www.coachfactoryoutletnew.com/ coach factory outlet
http://www.coachfactory-onlineoutlet.com/ coach factory outlet
http://www.truereligionbrandjeans.us.com/ true religion outlet
http://www.truereligionjeans.us.com/ true religion jeans
http://www.coach--handbags.com/ coach outlet online
http://www.louisvuitton--outlet.us/ louis vuitton outlet
http://www.timberland--shoes.com/ timberland boots
http://www.isabelmarantshoes.us.com/ isabel marant shoes
http://www.coachoutletonline-factory.com/ coach outlet online
http://www.michael-korsonlineoutlet.com/ michael kors outlet online
http://www.louisvuitton-handbag.us/ louis vuitton handbags
http://www.coach-outletstoreonline.com/ coach outlet store online
http://www.true-religion-jeans.com/ true religion jeans
http://www.coach-outletfactoryonline.com/ coach factory outlet online
http://www.coachfactoryoutlet-official.com/ coach factory outlet
http://www.louis-vuittonoutlets.com/ louis vuitton outlet
http://www.officialcoachonlinefactorysale.com/ official coach factory outlet
http://www.coachoutlet-storefactory.com/ coach outlet online
http://www.michael-korsoutletsonline.com/ michael kors outlet
http://www.tiffanysjewelry-co.com/ tiffany and co jewelry
http://www.celineoutlet-online.com/ celine outlet
http://www.celine-handbags.com/ celine handbags
http://www.toms--shoes.us/ toms shoes
http://www.fitflopsandalssale.com/ fitflops
http://www.fitflopusaonline.com/ fitflop outlet
http://www.prada-handbag.com/ prada handbags
http://www.tiffanyandcoinc.com/ tiffany jewelry
http://www.prada-outlets.com/ prada outlet
http://www.michael-korsoutletinc.com/ michael kors
http://www.marcjacobs.us.com/ marc jacobs
http://www.supra.us.com/ supra shoes
http://www.ralphlaurenpolo-inc.com/ polo ralph lauren
http://www.tiffanyjewelry.us.com/ tiffany jewelry


Add your comment on this article below:

Sorry, there's an error with your form entries. We really appreciate your comment, so please try again.

Form submitting now...

Name:

Website:

Email address (not displayed):

Enter your comment below: