Add to Favorites

Secure file download

Creating a secure file download script is pretty easy.
There are a few things you have to be mindful of:

  1. You must store the files in a directory not accessible from the web
    A lot of hosting providers give you a public_html directory where your web files go,
    you can create a folder one level above that, that is still accessible by a php script but not
    directly from the web.
  2. Your php application must have authentication of some kind

After the above has been satisfied, all that you have to do is create a php script that will make sure an authenticated user is logged in or that a pre-condition to download the file has been met then read the file out to the browser.

A quick example of a php script to do just that



$file = '../uploads/thefile.txt';

header('Content-type: application/force-download');
header('Content-Transfer-Encoding: Binary');
header('Content-disposition: attachment; filename="'. basename($file) .'"');
header('Content-length: '. filesize($file) );

readfile( $file );


This script is an example of how to set the header variables to force the browser to download the file, and how to proxy a file through php to the browser.

You have to implement your own authentication function, and make the download script handle the possibility of having a secure download of more than one file, but it can be used as a base to create more complex scripts.

Happy coding


Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up