Php Script for File Download

Downloading a file from the internet should work just like everything else does on the internet. It should be simple, easy, quick and without complications. This is an awesome php script that makes it easy to create a download script right on your server!

This is a full featured PHP script for safe, secure server-side file transfer and download. Nukefile came about as a result of the author looking for an open source solution. This script looks great, is easy to use and works for both commercial and personal needs.

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:

$path = “/absolute_path_to_your_files/”;
$secret = ‘your-secret-string’;
if (isset($_GET[‘fid’]) && preg_match(‘/^([a-f0-9]{32})$/’, $_GET[‘fid’])) {
$db = new mysqli(‘localhost’, ‘username’, ‘password’, ‘databasename’);
$result = $db->query(sprintf(“SELECT filename FROM mytable WHERE MD5(CONCAT(ID, ‘%s’)) = ‘%s'”, $secret, $db->real_escape_string($_GET[‘fid’])));
if ($result_>num_rows == 1) {
$obj = $result->fetch_object();
$fullPath = $path.$obj->filename;
if ($fd = fopen ($fullPath, “r”)) {
// Place here the other PHP download code
fclose ($fd);
} else {
die(‘no match’);
} else {
die(‘missing file ID’);

view rawdownload-mysql.php hosted with ❤ by GitHub

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:

$secret = ‘Add some secret strinhg here…’;
$file_id = 123; // or something else you got from your MySQL database
$slug = md5($secret.$file_id);
echo ‘
<a href=”’.$slug.'”>PHP download file via MySQL</a>’;

A Beginners Guide to PHP Download Scripts

Written by John Zenith on August 08, 2016 | Coding Tutorials

A Beginners Guide to PHP Download Scripts

Note: The author does not address handling security threats that are associated with the file download. This code is not intended for real-world use, without further security hardening. Please read the comments below for more details. Also, download this file for additional sanitation and security code.

In this tutorial, I’m going to show you how to write a PHP script that allows downloads.

To allow downloads from a server, you need to write a script that can communicate with it effectively.

PHP is a server-side scripting language and is well-designed for this task, with many versatile tools. I’m going to show you how to power the download using the HTTP header function.

Let’s take a look at the HTTP header function. This function is used to send a raw HTTP header to a client:

header( string, replace, http_response_code );

Let’s examine the three parts of that function:

  • string: This is a required parameter and specifies the header string to send.
  • replace: This is an optional parameter and its indicate whether or not to replace the previous header or add a second header. The default is TRUE which will replace the header, whereas FALSE allows multiple headers of the same type.
  • http_response_code: This is an optional parameter and forces the HTTP response code to the chosen value.

Here’s the function inside a complete download script:

 // check if the download button is clicked if ( isset($_POST['downloadButton'] )) { // check if the filename is set $filename = ( isset($_POST["filename"]) ? $_POST["filename"] : null ); // check if file is in the directory or on the server if ( file_exists( $filename )) { // download the file from the server header("Content-Type: application/octet-stream"); header("Content-Disposition: attachment; filename=filename here"); header("Content-Length: " . filesize( $filename) ); header("Cache-Control: must-revalidate"); readfile( $filename ); exit; } } 

You can click here to download a working copy of the code in this tutorial.

Let’s break down the examples of the HTTP header function in that code:


This declares the file as a binary and setting its type. The HTTP Header string parameter is set to Content-Type: application/octet-stream, or to the specified file type if needed. This enables the browsers to treat the file as a binary. Note that application/octet-stream can be used to dynamically refer to all file types.

header("Content-Type: application/octet-stream");


The HTTP Header string parameter is set to Content-Disposition: attachment. This forces the browser to display a download dialog box, thereby making the download possible.

header("Content-Disposition: attachment");

By using the HTTP header Content-Disposition: attachement, you can also supply or add a recommended filename to be displayed by the download dialog box. This is done using a concatenated filename attribute.

header("Content-Disposition: attachment; filename=file name here");

When no filename is specified, the current script filename is used. Also, avoid separating the attribute filename with a blank space like so, file name=file name here, because blank spaces will break the script.


The HTTP Header string parameter is set to Content-Length: filesize=file size here. This is used to display the file size information in the download dialog box. To easily get the file size, you will use the PHP filesize( ) function and pass the filename to its parameter.

header("Content-Length: filesize=" . filesize("file name here") );

Here is the filesize() function which returns the size of the specified file.

filesize( string filename );


The HTTP Header string parameter is set to Cache-Control: no-cache, or Cache-Control: must-revalidate. This is because most information about the file is cached, so it’s important to control the cache.

header("Cache-Control: no-cache");

The readfile function

To retrieve the actual file contents form the server, you can use the PHP readfile() function. This file function comes in handy because you don’t necessary need to write any conditional loop statements to loop over all of the file’s data.

This function reads a file and writes it to the output buffer. It returns the numbers of bytes read on success, or FALSE and an error on failure.

readfile( filename, include_path, context );
  • filename: This is a required parameter. It specifies the file to read.
  • include_path: This is an optional parameter. Set this parameter to ‘1’ if you want to search for the file in the include_path (in php.ini) as well.
  • context: This is an optional parameter. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream.

Security checks and limitations

To prevent the user from downloading any files from the server by altering the script, the filename should not be passed as a query string in the URL using the $_GET method. Always use the $_POST method to send the filename along with the form whenever it is submitted.

You can use the HTTP header Content-Type : file type to limit the files users can download from the server. For example, if you have an image file with .png extension on the server, and you want users to be able to download it, instead of using Content-Type: application/octet-stream, you can set Content-Type header to the specified file type like so – Content-Type: image/png. This will limit the types of file users can download, and also, prevent them from downloading sensitive content from the server.

Why is this important? If you send a URL query like so localhost/download.php?filename=download.txt, the user can try to manipulate the URL query and change it from ?filename=download.txt to this – ?filename=anything. Or the user may try a URL query injection, which might break your script.

Downloading Files with PHP

Normally, you don’t necessarily need to use any server side scripting language like PHP to download images, zip files, pdf documents, exe files, etc. If such kind of file is stored in a public accessible folder, you can just create a hyperlink pointing to that file, and whenever a user click on the link, browser will automatically downloads that file.


Try this code »

<a href="downloads/">Download Zip file</a>
<a href="downloads/masters.pdf">Download PDF file</a>
<a href="downloads/sample.jpg">Download Image file</a>
<a href="downloads/setup.exe">Download EXE file</a>

Clicking a link that points to a PDF or an Image file will not cause it to download to your hard drive directly. It will only open the file in your browser. Further you can save it to your hard drive. However, zip and exe files are downloaded automatically to the hard drive by default.


This tutorial shows how you can use PHP to generate an executable file with a PHP script. When the user clicks on the downloaded file, it will run the PHP script which will in turn download and save data from a remote server.


No Comment.