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

wky*_*yip 5 php pdf

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

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

Bru*_*uce 4

使用此代码...

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

RewriteEngine on
RewriteRule .* your-php-script.php
Run Code Online (Sandbox Code Playgroud)

现在该文件夹中的 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);
Run Code Online (Sandbox Code Playgroud)