Search code examples
phpmysqlapachedownloaddigital-downloads

PHP: How to protect digital products(video, audio, ebook, etc.) from unathorized downloading?


How to protect digital products(video, audio, ebook, etc.) from unauthorized downloading? I'm using Apache server and PHP/MySQL. Please help!

Thanks! Paul G.

Edited: Sorry for the incomplete question. What I want is to avoid other members from sharing direct download links to the files they have access to non-members. I heard something that it can be done by storing digital products outside the root folder, but I have no idea how to exactly implement it with PHP.


Solution

  • I'm going to assume that you're trying to protect files that should only be available to "logged-in" users... if you're just trying to stop people from downloading files that are embedded in your site there is really nothing you can do.

    So, operating on the premise that you're trying to allow file-access/download only to approved users, your best bet is to only serve protected content through a php controller file (let's call it serve_file.php). You store the actual files outside the public root directory (or some other inaccessible folder) or you store the files as BLOB data in a MySQL table.

    Then, when a user wants to download a file will be provided with a link to serve_file.php with some _GET data which identifies the file they're trying to get:

    http://mysite.com/serve_file.php?file_id=24, for instance.

    The serve_file.php script takes the _GET data, figures out which file it's indicating, and then checks a permissions table (or just checks to see if the user is logged in) and decides whether the user is eligible to receive the file. If they are, it gets the file data (either from MySQL or with file_get_content()), spits out appropriate headers (depending on what type of file you're serving up) and then print/echos the content:

    //check that the user is logged in (I'm assuming you have a function of this name)
    if (!user_logged_in()){
       die('You do not have permission! Please log in');
    }
    
    /*see what file the user is trying to get... 
    this is a very simple sample that can only get PDFs.
    You should probably have a table with file details*/
    $file_location = $_SERVER['DOCUMENT_ROOT'].'/../protected_files/file_'.intval($_GET['file_id']).'.pdf'
    if (!is_file($file_location)){
       die('Could not get that file!');
    }
    
    $content = file_get_contents($file_location);
    header("Content-Type: application/pdf");
    header("Content-Length: ".strlen($content));
    //add some more headers here, to deal with caching, etc
    echo $content;
    die();
    

    The headers you've set tell the user's browser how it should interpret the data you're sending (for instance, as an Content-Type: application/pdf) and you've successfully allowed only authorized users from accessing the document because they always have to go through your PHP authentication script.