FORMfields, the premiere web framework
Login
Support Home | Knowledge Base | Documentation | Forums | Contact Us
Info
Secure :: Miscellaneous

Password Protecting Downloads

(2840 views. Last Updated: 2009-06-15 12:16 PM)

You can use the following method to password protect file downloads. In this example, we will assume that you have a directory called, "downloads" in the root directory of your website and that you wish to password protect a file in this directory called, "myFile.zip". We also assume that you want to restrict access to this file to only those users that are in the group called, "Managers".

1. Create a file called "downloadMyFile.php", place the following code in this file and place this file in the root directory of your website.
<?php

    
// BEGIN: Secure Protection Code
    
require_once($_SERVER["DOCUMENT_ROOT"] . "/secure/globals.php");
    
verifyMembership("Managers");
    
// END: Secure Protection Code

    
function printDownloadPage($path$filename=null)
    {
        if (
$filename == null)
            
$filename basename($path);
        
header('Content-type: application/zip');
        
header('Pragma: '); // Needed for SSL in IE
        
header('Cache-Control: '); // Needed for SSL in IE
        
header('Content-Disposition: attachment; filename="' $filename '"');
        
$size filesize($path);
        
header("Content-Length: "$size " bytes");
        
readfile($path);
    }

    
printDownloadPage($_SERVER["DOCUMENT_ROOT"] . "/downloads/myFile.zip");
    exit;

?>

2. Now, you can use the link http://example.com/downloadMyFile.php to point a user to this download and this link will require that the user is logged in and in the group "Managers".

3. This last step is optional, but without it, users will still have access to your downloads if they can guess the filename of the download.

- Option A - Most Secure:
You can place your downloads in a directory that is above the root directory of your website so that users cannot directly download your files. Then, just modify the paths above accordingly. Most web servers support this configuration.

- Option B:
You can use .htaccess files to protect the downloads directory. You won't actually need to remember to distribute the .htaccess password, but it will keep users from directly downloading the files. Please see http://formfields.com/FORMfieldsArea/FORMfields3/tutorials/htaccess.php for more information.

- Option C:
On most web servers, you can set the permissions on the download file, e.g. "myFile.zip" to "chmod 000" (no permissions). downloadMyFile.php will still be able to access the file, but the user will no longer be able to download it directly from the browser.
Info
Support | Earn Money
Copyright © 2005-2019 Brain Book Software LLC.
Built with FORMfields, the premiere web framework.