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>";


} elseif (!file_exists($filename)) {

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



switch ($file_extension) {

case "pdf":

$contenttype = "application/pdf";


case "jpg":

$contenttype = "image/jpg";



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

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



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") {



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";


case "zip":

$contenttype = "application/zip";


case "doc":

$contenttype = "application/msword";


case "xls":

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


case "ppt":

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


case "gif":

$contenttype = "image/gif";


case "png":

$contenttype = "image/png";



$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.


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?



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?



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/
Michael Kors Outlet
Discount Michael Kors
Michael Kors Outlet
Michael Kors Factory Store
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

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

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

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

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

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

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

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...



Email address (not displayed):

Enter your comment below: