PHP file download script

Posted by Olaf #

This is my favorite PHP download script. I had been using something else 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 the 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 the web browser.

How to use the PHP download Script?

Create a PHP script, name it "download.php" and copy/paste the following code:


set_time_limit(0); // disable the time limit for this script

$path = "/absolute_path_to_your_files/"; // change the path to fit your websites document structure
$dl_file = preg_replace("([^\w\s\d\-_~,;:\[\]\(\].]|[\.]{2,})", '', $_GET['download_file']); // simple file name validation
$dl_file = filter_var($dl_file, FILTER_SANITIZE_URL); // Remove (more) invalid characters
$fullPath = $path.$dl_file;

if ($fd = fopen ($fullPath, "r")) {
    $fsize = filesize($fullPath);
    $path_parts = pathinfo($fullPath);
    $ext = strtolower($path_parts["extension"]);
    switch ($ext) {
        case "pdf":
        header("Content-type: application/pdf");
        header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a file download
        // add more headers for other content types here
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
    header("Content-length: $fsize");
    header("Cache-control: private"); //use this to open files directly
    while(!feof($fd)) {
        $buffer = fread($fd, 2048);
        echo $buffer;
fclose ($fd);

Create on your webpage links to the files which resists in a password protected directory or in a directory above the website root directory. Use for our example on the file name.

<a href="download.php?download_file=some_file.pdf">Download file</a>

PHP download script 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!).

Script Demo

The demo page demonstrates the PHP code examples for file upload and download and PHP directory functions to show files in SELECT menu.

Comments / discussions

Posted by dushyanta #

Hey I am a newbie to php.
I am trying to export (download) excel files from my server, but I get garbage values inside the downloaded file. I tried is also with jpg files and here I get the same result. Any idea what I'm doing wrong?

Posted by Olaf #

You're using the same PHP code as posted here on the page?

Double check the file paths, If your work with PHP files functions, it's easier to use absolute paths. For this beginner it's easier to use a password protected directory that is accessible via the web browser. Place inside that directory a PHP script with this code (the output is the absolute path from the directory).

echo dirname(__FILE__);

Posted by natsort #

Hi, The script works perfect for me.
But how to redirect to a different website or page after the download has started?

When I add the HTML <a rel="nofollow" href="download.php?download_file=some_file.pdf">Download here</a> to my main page, it just downloads the file. But I like to provide some information to the user afterwards.

Posted by Olaf #


if someone has clicked the download link, a PHP script is called and the output is send to the browser. You can't add any information here. It's possible to create some message on the page where the download link resists. You need to use some client side code on that page:

<a href="file.pdf" onclick="someJSfunction()">Download here</a>

After the download link was clicked, the JavaScript function will change the content on your downloads page.

Check my download page, that one works with a slightly modified version of this download script. I use the META refresh tag to start the download after X seconds. In that case I send the user to a single page using a special URL which contains a part of the file name.

Posted by MetalHippy #

Just registered to say what a great script this is - I use a host which prevents direct file downloads and this is just what I was looking for.

Keep up the good work, and thanks from me! :D

Posted by Dunxmax #

Thank you for this script - it does exactly what it says.

I am not a programmer, but am trying to add a bit more functionality when the user hits the download button. What I would like to be able to do is to send an auto email at the same time.

Up until I found your script I had managed to get an auto email to work which then linked back through an email to being able to download a file.

I want to find out if it is possible to do both at the same time and how to do it. I tried putting both scripts in the same php file, but this didn't work.

If anyone can point me in the right direction that would be great.

Posted by Olaf #

Hi Dunxmax,

Sure this is a great function but is not really related to this PHP download snippet ;)

I think you need something different like:

  • Create a mailing list using MailChimp
  • Place a subscribe now form on your website
  • Use some download link in your welcome email message.
    • This way you can collect the email addresses too without building a web application for this. Place on your subscribe form also a checkbox with the question if the subscriber like to receive future email messages.