Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating unique download link to download once only

Tags:

http

php

I wanna create a few unique download link for my users. The reason is that I wanted to let them download once only, so that they can use back the same link to download again.

I've generate a few of the keys (example, qwertyasdfghzxcbn. As in the download link will be like www.xxxxx.com/download.php?qwertyasdfghzxcbn) in the database and flag field where when the user downloaded, it will update 1 to the flag field.

I did a search on the net and found this. http://www.webvamp.co.uk/blog/coding/creating-one-time-download-links/

But that only works when you go to the page first then only the page will generate the unique link. I've already pre-generate the link inside my database, I don't need to regenerate again, if fact if I generate the key when user go the page, they will able to download multiple times by refreshing the page.

like image 224
Adam Smith Avatar asked Sep 18 '13 08:09

Adam Smith


1 Answers

The solution would be to make the link target itself a PHP script.

You'd hide the actual file somewhere inaccessible from the browser (i.e., somewhere where you can reach the file via fopen(), but isn't within the document root), and put a download.php file to download files.

The download script itself would look something like this:

$fileid = $_REQUEST['file'];
$file = file_location($fileid); // you'd write this function somehow
if ($file === null) die("The file doesn't exist");
$allowed = check_permissions_for($file, $fileid) // again, write this
// the previous line would allow you to implement arbitrary checks on the file
if ($allowed) {
  mark_downloaded($fileid, $file); // so you mark it as downloaded if it's single-use
  header("Content-Type: application/octet-stream"); // downloadable file
  echo file_get_contents($file);
  return 0; // running a return 0; from outside any function ends the script
} else
  die("You're not allowed to download this file");

Any link you point would simply point to download.php?fileid=712984 (whatever the fileid actually is). That would be the actual download link, since that script does transfer the file; but only if the user is allowed to retrieve it. You'd have to write the file_location(), check_permissions_for() and mark_downloaded() functions yourself though.

like image 107
aaaaaa123456789 Avatar answered Sep 19 '22 18:09

aaaaaa123456789