This is my favorite PHP download script. Before I’ve used a different more simple method, until a client wanted to be able to allow their site visitors to download a large file from a password protected directory. The PHP script works on Apache web servers for all kind of files. I have used this script for file downloads even bigger than 500MB. The cache control header is used to force a download for text files or other files, even if they are opened by default inside your web browser.
How to use the PHP download file script?
Create a PHP script, name it “download.php” and copy/paste the following code:
Create on your web page links for all the file which resists in a password protected directory or in a directory above the website root directory. Use for our example the following download URL:
PHP download file features:
- The file name, which is passed via the query string, is sanitized by using the PHP function preg_replace() and filter_var()
- To make the script safer, I use the PHP function pathinfo() to parse the file path, if this happens successfully, the script will continue the further file handling process.
- The file download script is also useful for bigger files (using this script I’ve downloaded files bigger than 500MB!).
The demo page demonstrates the PHP code examples for file upload and download and PHP directory functions to show the files in a SELECT menu.
PHP download files from a MySQL database
The PHP download code doesn’t hide the file name and in some situations it might be better to use a unique string or ID as a key for the file download. With the following example, I will use a string to receive the name of a file which is stored inside a secure MySQL database. Let say, we have a simple database table with only two columns for the ID and the filename. The code for the file download.php is almost the same and only the first part is different:
How to use that PHP/MySQL download code?
In the first example I used the file name inside the download URL. Because I’m casting the md5() encryption with $secret as the salt, I need to built my file download URL differently:
I published the PHP download example code to explain how a write a PHP download file script . If you really need to protect your downloads, you need to deny the direct access of the file location using Apache directives or .htaccess rules. Use more secure slugs to receive a file name from your database. For example you can encrypt the database row key as well.
Published in: PHP Scripts