Download files through authentication

Last updated: Jul 6, 2007

I recently needed to implement a way for authenticated users to download files. Normally to host a file for download on a site you would need to provide the url to the download. www.yourdomain.com/restrictedfile.pdf.

You could then authenticate the user and only provide the link if the user was authenticated; however, there is nothing preventing users from simply typing the url into the browser and downloading the sensitive information.

This is why i created a script with php to fetch the file only when the user session is active. The restricted files are on the webserver but stored in an a directory that Apache has no access to.

$file = $_GET['file'];
$download_folder = '../RestrictedFiles';

$file = basename($file);
$filepath = "$download_folder/$file";

if (file_exists($filepath)) {

    //.... check to see if user is logged in ...
    // connect to database

    // include auth and nav

    // close mysql connection

    header("Content-type: application/octet-stream");
    header("Content-Disposition: attachment; filename=$file");
    session_write_close();
    readfile($filepath);

} else {
    echo 'The file you are trying to download is not found.  If you think this is an error 
                 please <a href="/contact/">contact</a> us.';
}

To see an example in ASP see: ASP Example

Need to print shipping labels on your site?

Checkout my product RocketShipIt for simple easy-to-use developer tools for UPS™ FedEx™ USPS™ and more.

Get notified on new posts or other things I'm working on

Share: