PHP - 保护通过直接链接访问的PDF文件


PHP - Protect PDF file being access by direct link

我的服务器中有一个PDF文件,并且有一个PHP页面可以在一些凭据验证(例如密码验证)后强制下载PDF文件,但是如果用户能够知道PDF文件的直接链接,他们设法查看/下载它而无需经过凭据验证。

有什么方法可以保护通过直接链接(如 http://domain.com/mypdf.pdf)访问的PDF文件?

使用此代码...

最好的方法是 保护该文件夹 htaccess ,如您所提到的。因此,您将所有 PDF 放在pdf/文件夹中,并放在您放置文件的同一pdf文件夹中.htaccess

RewriteEngine on
RewriteRule .* your-php-script.php

现在,此文件夹中的 url 无法访问任何文件。对此文件夹中的文件的每个请求都将返回脚本返回的内容your-php-script.php。在your-php-script.php你做这样的事情:-

//Check if user has right to access the file. If no, show access denied and exit the script.
$path = $_SERVER['REQUEST_URI'];
$paths = explode('/', path);
$lastIndex = count($paths) - 1;
$fileName = $paths[$lastIndex]; // Maybe add some code to detect subfolder if you have them
// Check if that file exists, if no show some error message
// Output headers here
readfile($filename);