How to: Use PHP to Force a File Download
By Aaron F. March 18th, 2014
Hello there, and welcome to my new & improved website!
I've realized it has been an awfully long while since I took the time to write a blog post. Im going to kick off my websites redesign with this brand new post about how to use PHP to force a file to be downloaded, from either a local & external server.
This script may come in handy if you wish for your users to download a file directly to their computer. This is especially handy when the file type in question is one which will normally display within the browser (PDF, HTML, TXT, & images, for example).
The great thing about this script, is it's universal application, and the fact it will work with external files not hosted on the same server as where the script is located.
This script is used by accessing the following URL, on your own server. Be sure to change the domain names & file URL to suit your needs: http://www.mywebsite.com/download.php?id=http://www.some.com/file/here.pdf
Place the following code in your download processor file. We will call it download.php:
Im going to start by breaking the code down from the outside in. This script has some very basic security built in, mainly to prevent direct access to the download.php file. If you look closely at the code, you will see an IF and ELSE statement. For the beginner, this simply means that IF a specific rule is met, do this. If not (ELSE) do something else.
In this specific case, IF a GET variable called "id" is defined as part of the URL, the code will set the header information required to force the file download. Otherwise, if the GET variable is not set in the URL, or the GET variable is defined as anything other than "id," the code will ignore it and redirect to http://www.mywebsite.com/error/.
Line 3 is the name of the file to be downloaded. In this case, it is defined in the GET variable attached to the download.php file URL, like this: download.php?id=[URL TO DOWNLOAD GOES HERE!]
Lines 4 thru 6 tell the server how to treat the file that will be downloaded. Line 4 tells the server that the file is to be downloaded, line 5 sets the file mime type, in this case application/octet-stream is a general mime type which is applied to files that must be downloaded, like an .EXE or .ZIP file. This overrides server & browser default handling for files that would normally render within the browser itself, such as images, PDF, and HTML files.
Line 7 is where the final command is given to the server to read the file, along with all the defined header information. This results in the file being downloaded by the browsers normal method.
That wraps up todays script tutorial. I hope you enjoyed the post & will find use with this little gem of s script. It is definitely handy when the situation calls for it!
Categories: Web Design & Development