You can do this by creating a htaccess rewrite to refer the user to a PHP script:
RewriteEngine On
RewriteRule ^download/([^/]+) /lib/download.php?file=$1 [QSA]
This will forward any request to yourdomain.com/download/anyfilehere.mp3?one_time_token=ABCDEFG
to lib/download.php
and set the $_GET['file']
to be anyfilehere.mp3
. The one_time_token
$_GET
parameter will be forwarded, as we used [QSA]
.
The download.php
could simply look something like this:
<?php
if (!empty($_GET['file'])) {
if (!empty($_GET['one_time_token'])) {
if (TokenOK($_GET['one_time_token'])) { //Create a function called TokenOK where you look up the download token in eg. a database
$fileName = '/var/www/downloadfolder/' . $_GET['file'];
if (file_exists($fileName)) {
ExpireToken($_GET['one_time_token']); //Create a function called ExpireToken where you expire the token in eg. the database
readfile($fileName); //Read the file to the user
die();
} else {
die('Error: file not found');
}
} else {
die('Error: token is not OK');
}
} else {
die('Error: token is not specified');
}
} else {
die('Error: file is not specified');
}
?>
Things to consider:
- Output a mime header type specifying the content-type of your file
- Read this PHP manual entry on
readfile
- Limit the one time token to only be valid in a certain time frame (and notify your user of this), instead of allowing it to be downloaded only once
- How will your system react if the user cancels the download, and therefore can't download it again?
- What if the download fails? Do they need to request a new download link?
- If it's a streaming MP3 file, make sure that seeking works (it most likely won't if you seek outside where the MP3 has streamed to, as it'll create a new request for the MP3 file)