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 the used the script with files bigger than 10MB. I added the cache control header to also download 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:

<?php

ignore_user_abort(true);
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
$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
        break;
        // add more headers for other content types here
        default;
        header("Content-type: application/octet-stream");
        header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        break;
    }
    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);
exit;

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:

  • File names are sanitized by using the PHP function preg_replace()
  • The PHP function pathinfo() is used to parse the file path, this way only the script is used in the further file handling process.
  • The file download script is 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).

<?php
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 #

Hi,

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.