View Single Post
Old 2007-09-01, 22:06   Link #3
SeijiSensei
AS Oji-kun
 
 
Join Date: Nov 2006
Age: 74
You need to write a PHP wrapper that keeps track of the number and sizes of the files downloaded. (The simplest way would be to write running totals to a text file in a directory to which the web server user has rights.) When the limits are exceeded the wrapper displays a "sorry, no more today" message. I'd have it record the time of day in the file as well; the first time the script is accessed after midnight you'd just zero the totals.

I've used a wrapper like this to limit file downloads to authorized users. Here's a code snippet:

Code:
<?php
### NO TEXT CAN BE ECHOED BEFORE HERE ###

### SEND HEADERS ###
header("Content-Type: ".$thisdoc["mimetype"]);
header("Content-Disposition: inline; filename=".$thisdoc["filename"]);

### Open the file and display it
$fp=fopen("/path/to/".$thisdoc["filename"],"r");
fpassthru($fp);
fclose($fp);
?>
These commands send two HTTP headers that tell the client the name and mimetype (e.g., "video/x-matroska") of the content to be transferred, then opens the file and sends it unaltered to the client with the fpassthru() command. There can be no text outside the php tags before the header() commands or you'll get an error. (Blank spaces outside the php tags are sent directly to the client. Once any text is sent you've ended the HTTP dialogue so you cannot send the headers. If that's not clear it's discussed in the PHP manual.) The script must have the <?php start tag in column 1, line 1 of the script and all text before the fpassthru() command must reside inside the php tags.

I usually manage this stuff by storing the information about the files in a database (PostreSQL is my choice), but that might be overkill for you. An easier solution is to write the download URIs in a form like "/getfile.php?name=myfile.ext" and have the script use the file's extension to determine which mimetype to send in the HTTP headers. A simple PHP array like :
Code:
$mimetypes=array("mkv"=>"application/x-matroska","zip"=>"application/x-zip",etc.)
that maps extensions to mimetypes should be easy to whip up if you aren't distributing a very wide variety of filetypes.

I leave the rest as an exercise for the reader.

Last edited by SeijiSensei; 2007-09-02 at 10:33. Reason: fixed typo in array definitions
SeijiSensei is offline   Reply With Quote