我的服务器中有一个 PDF 文件,并且有一个 PHP 页面可以在一些凭证验证(例如密码验证)后强制下载 PDF 文件,但是如果用户能够知道他们设法获取的 PDF 文件的直接链接无需通过凭证验证即可查看/下载它。
是否有任何方法可以保护通过直接链接访问的 PDF 文件,如 http://domain.com/mypdf.pdf ?
最佳答案
使用此代码...
正如您所提到的,最好的方法是使用 htaccess
保护该文件夹。因此,您将所有 PDF 放在 pdf/
文件夹中,并在您放置 .htaccess
文件的同一个 pdf
文件夹中:
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);
关于PHP - 保护通过直接链接访问的 PDF 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30935833/