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 website I wrote this small function to help me doing this 🙂

 function ForceDownloadImage($path_to_image)
  	//get filename
  	$filename = basename($path_to_image);
  	//sent the right headers
	header("Content-Transfer-Encoding: binary");
	header("Content-Type: image/jpg");
	header("Content-Disposition: attachment; filename=$filename");
	//start feeding with the file

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


Here is a test file for it :

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

5 comments on “How to force a file download

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.