10

我想为我的用户创建一些独特的下载链接。原因是我想让他们只下载一次,以便他们可以使用相同的链接再次下载。

我在数据库和标志字段中生成了一些密钥(例如,qwertyasdfghzxcbn。因为下载链接将类似于 www.xxxxx.com/download.php?qwertyasdfghzxcbn),当用户下载时,它将更新 1到标志字段。

我在网上搜索了一下,发现了这个。 http://www.webvamp.co.uk/blog/coding/creating-one-time-download-links/

但这仅在您首先访问该页面时才有效,然后只有该页面会生成唯一链接。我已经在我的数据库中预先生成了链接,我不需要再次重新生成,如果我在用户访问页面时生成密钥,他们将能够通过刷新页面多次下载。

4

2 回答 2

9

解决方案是使链接目标本身成为 PHP 脚本。

您会将实际文件隐藏在浏览器无法访问的某个地方(即,您可以通过 访问该文件fopen()但不在文档根目录中的某个地方),并放置一个 download.php 文件来下载文件。

下载脚本本身看起来像这样:

$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");

您指向的任何链接都只是指向 download.php?fileid=712984 (无论 fileid 实际是什么)。那将是实际的下载链接,因为该脚本确实传输了文件;但前提是允许用户检索它。不过,您必须自己编写file_location(),check_permissions_for()mark_downloaded()函数。

于 2013-09-18T08:43:20.090 回答
0

我建议使用 uniqid() 函数,并将具有过期日期的唯一 ID 存储在数据库中,同时返回用户 url,如下所示: ...?file_id=$id

打开链接时,您可以将其从数据库中删除或将其标记为“很快”删除(以防用户想要刷新页面。)

于 2013-09-18T08:36:18.910 回答