我试图限制直接访问目录中的文件。例如,我有
website.com/files/example.flv。
因此,如果用户直接转到URL中的文件,我希望他们被重定向到主页。
我已经尝试使用htaccess的以下内容
deny from all
但效果不佳。有没有一种方法可以使用php做到这一点,然后在用户直接进入url中的文件时,它们将被重定向。
因此,如果用户转到url中的文件链接,他们将被发送到主页。所以只能使用htaccess做到这一点
最佳答案
如果要限制对文件的访问,则应考虑将它们存储在公共(public)DocumentRoot外部,并使用自己的访问逻辑使用PHP来交付文件。这意味着在www或public_html文件夹之外,具体取决于您正在使用的托管环境。
<?php
// Suppose your "public_html" folder is .
$file = './../data/test.gif';
$userCanDownloadThisFile = false; // apply your logic here
if (file_exists($file) && $userCanDownloadThisFile) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename=filename.gif');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
}