PHP - Protecting digital Downloads
Asked Answered
A

3

6

I'm trying figure out how I can protect digital downloads in PHP. Just need some general directions so I can start my research. I don't seem to be able to find anything useful.

I want to make files available for my users to download but don't want them to be able to directly access a download folder. Also, I want the download link to be available only for set period of time or a single download.

Could some one point me in the right direction?

Anhinga answered 23/3, 2011 at 22:16 Comment(3)
<rant>As opposed to analog downloads?</rant> @usniorg, can you tell us what web server software you use, please? It will impact the answer.Illusory
store files out side web root, serve via scriptBrythonic
@BoltClock, You mean to actually store the files in the database? Is that a good idea? Sorry I'm not sure what you mean.Anhinga
S
10

The best way is to delegate the download managment after your check to the mod for apache

x_sendfile

https://tn123.org/mod_xsendfile/

Usage:

<?php
...
if ($user->isLoggedIn())
{
    header("X-Sendfile: $path_to_somefile");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=\"$somefile\"");
    exit;
}
?>
<h1>Permission denied</h1>
<p>Login first!</p>

Basically when you send the header X-Sendfile the mod intercepts the file and manages the download for you (the file can be located whenever you want outside the virtualhost).

Otherwise you can just implement a simple file download.php that gets the id of the file and prints the contents with readfile after the login check

Staub answered 23/3, 2011 at 22:22 Comment(1)
It's worth noting that X-Sendfile support is also available in nginx and lighttpd (which is where it originated), and is the best option if it's available to you.Illusory
B
1

Just some examples: You can place your files outside of the webserver's document root or in a directory that is protected by a .htaccess file with a "deny from all" rule; then you deliver the files by a custom PHP function that sets the correct headers (mime-type, filesize etc.) and returns the file.

You could create links with unique id's based on MD5 or SHA1 hashes - a mod_rewrite rule points the id to your PHP file, you lookup the id in the database and do your time checks, like

example.com/downloads/73637/a8d157edafc60776d80b6141c877bc6b

is rewritten to

example.com/dl.php?id=a8d157edafc60776d80b6141c877bc6b&file=73637

Here's an example of doing something you want with nginx and PHP: http://wiki.nginx.org/HttpSecureLinkModule

Borscht answered 23/3, 2011 at 22:29 Comment(0)
M
0

"Secure Download Links", a PHP Script can be used to hide download url or rename download file, it has option for storing below web root and for files stored above webroot that is with absolute http urls also.

Measurement answered 30/6, 2014 at 18:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.