This is my favorite PHP download script. 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 bigger than 500MB. The cache control header is used to force the download for text files and 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 each 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 created 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 files in 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 download. With the following example, I will use a string to receive the name of a file which is stored inside a MySQL database. Let say we have a simple database table with only two columns for the ID and the filename. The code for the 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 right in my 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 file download using a PHP script. If you really need to protect your downloads, you need to deny the direct access a safe location 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