Skip to content


How to force a file download

I’m working on a big script for Greg, a client of mine. He needed a way so the user can download an image without using the common method (right click on the image and then ‘Save image as’) but using a normal browser download box.
After few minutes of searching the www.php.net website I wrote this small function to help me doing this :)

  1. function ForceDownloadImage($path_to_image)
  2.  {     
  3.         //get filename
  4.         $filename = basename($path_to_image);
  5.         //sent the right headers
  6.         header("Content-Transfer-Encoding: binary");
  7.         header("Content-Type: image/jpg");
  8.         header("Content-Disposition: attachment; filename=$filename");
  9.         //start feeding with the file
  10.         readfile($path_to_image);
  11.  }

The “$path_to_image” variable can be an absolute path (“/dir1/dir2/file1.txt”), a relative path (“dir1/file1.txt”) or an URL (“http://www.domain.com/txt/abc.txt”).
The function will return a download box :

download_box.GIF

Here is a test file for it :

  1. <?php
  2.  include("the file where we have the function");
  3.  //be sure to not output anyting to the browser
  4.  //in the code above this function call !!
  5.  ForceDownloadImage("www.php.net/images/php.gif");
  6. ?>

If you use this function then be very carefull as it can force download any type of file if used wrong!
So don’t “trust” your users and provide the script with a parameter in this form (force_download.php?path=/images/test.gif) but use a more secure way (for example : I have a DB table with all the images path and I give as a parameter only the imageID and based on it I retrieve the real path to the file )!!
I hope this will help someone

Posted in PHP Tips & Tricks.


5 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Vinay R. says

    Nice code ! Thanks

  2. Trimbitas Sorin says

    You are welcomed :)

  3. Kai says

    Nice, but it gives a
    Cannot modify header information – headers already sent
    Error when you include the top code in the bottom.

  4. Trimbitas Sorin says

    It means that you send in the download page ,before calling ForceDownloadImage function, another header (or maybe just a text using print/echo).
    Hope this helps

  5. Thomas Christian says

    Nice post, helped me, thanks!

    P.S.: “de pe net” ei? :)



Some HTML is OK

or, reply to this post via trackback.


Get Adobe Flash playerPlugin by wpburn.com wordpress themes