Download file script in PHP

Some times we  need to create a download link of any file in our site. We can point a direct link of the file to download but in this case we can get the absolute path of that file which is not preferred to us. Moreover some browsers redirect the download link path in a new window.

Hence we can create a separate PHP script through which we can download any file and there will be no possibility to access the absolute path of the file and no redirection to the other page. We can get the save file pop window in the same window.
Step 1: Create a PHP file named download.php and put the following codes in it.

<?php
$filename = $_GET['filename'];
// Modify this line to indicate the location of the files you want people to be able to download
// This path must not contain a trailing slash. ie. /temp/files/download
$download_path = "";
// Make sure we can't download files above the current directory location.
if(eregi("..", $filename)) die("I'm sorry, you may not download that file.");
$file = str_replace("..", "", $filename);
// Make sure we can't download .ht control files.
if(eregi(".ht.+", $filename)) die("I'm sorry, you may not download that file.");
// Combine the download path and the filename to create the full path to the file.
$file = "$download_path$file";
// Test to ensure that the file exists.
if(!file_exists($file)) die("I'm sorry, the file doesn't seem to exist.");
// Extract the type of file which will be sent to the browser as a header
$type = filetype($file);
// Get a date and timestamp
$today = date("F j, Y, g:i a");
$time = time();
// Send file headers
header("Content-type: $type");
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
header('Pragma: no-cache');
header('Expires: 0');
// Send the file contents.
set_time_limit(0);
readfile($file);
?>
view raw download.php hosted with ❤ by GitHub

Step 2: Now wherever you want to put the download file link, put the following code:

 <a href="download.php?filename=yourfilename.zip">Click here to Download the File</a>

Share this article:

5 thoughts on “Download file script in PHP”

Leave a Reply

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