php - 防止共享下载 URL

标签 php download

问题

当我向用户提供下载时,我不希望他们能够复制 URL 并与他人共享。更进一步:我只想提供一次下载。如果他们第二次访问该 URL,我想抛出一个 404。

问题

如何防止用户第二次访问下载 URL,这种方法是否充分证明。

附加信息

我目前按如下方式提供我的文件:

header("Content-type: application/pdf");

// Set the name of the downloaded file here:
header("Content-Disposition: attachment;filename='example.pdf'"); 

 // Get the contents of the original file:
echo file_get_contents('example.pdf');

我还在我的mysql数据库中添加了一个表

+----+------+-------+------+
| downloads                |
+----+------+-------+------+
| id | file | token | flag |
+----+------+-------+------+

最佳答案

您需要使用重定向到文件的下载脚本。在重定向到文件之前,脚本需要通过唯一 token (存储在数据库中)验证 url。该脚本可以记录已经进行的下载并在数据库中设置一个标志。检查标志以防止将来下载。

编辑:这是一个示例(带有伪代码):

if( isset($_GET["token"]) && !empty($_GET["token"]) )
{
    //verify $_GET["token"] matches a token in the db

    //verify that the download flag has not been set

    header("Content-type: application/pdf");

    // Set the name of the downloaded file here:
    header("Content-Disposition: attachment;filename='example.pdf'"); 

    //set the downloaded flag in the database so that this file can't be downloaded again

     // Get the contents of the original file:
    echo file_get_contents('example.pdf');
}
else
    header("HTTP/1.0 404 Not Found");

关于php - 防止共享下载 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27920688/

相关文章:

c# - 强制下载文件,默认不在浏览器上打开它

linux - 如何查看哪个 PHP 脚本消耗的内存最多?

php - 匹配出现在 XML 节点内的 ">"、 "<"、 "&"字符的正则表达式

javascript - 在客户端系统中使用客户端脚本的文件下载选项

java - 有没有办法从 jtable 下载选定的行?

java - 下载文件并保存到光盘不起作用

php - 保存后的 Laravel 关系可用性()

php - 具有结构化内容的单个 PHP 页面的模板引擎?

php - 在我的核心 PHP 站点或 CodeIgniter 站点上显示 Woocommerce 产品和 Magento 产品

java - 文件下载 SSLHandshakeException