php限制对目录中文件的访问
我试图限制对目录中文件的直接访问.所以例如我有website.com/files/example.flv.
I am trying to restrict direct access to files in a directory. So for example i have website.com/files/example.flv.
因此,如果用户直接访问 URL 中的文件,我希望他们被重定向到主页.
So if users go straight to the file in the URL, i want them to be redirected to the home page.
我使用 htaccess 尝试了以下操作
I have tried the following using htaccess
deny from all
但效果不佳.有没有一种方法可以使用 php 执行此操作,然后在用户直接转到 url 中的文件时,他们将被重定向.
but its not working great. Is there a way i could do this using php, then in the user goes straight to the file in the url, they will get redirected.
因此,如果用户转到 url 中的文件链接,他们将被发送到主页.所以这只能使用 htaccess 来完成
So if the user goes to the file link in the url, they will be sent to the home page. So can this only be done using htaccess
推荐答案
如果您想限制对文件的访问,您应该考虑将它们存储在公共 DocumentRoot 之外并使用 PHP 来交付文件,应用您自己的访问逻辑.这意味着在 www 或 public_html 文件夹之外,具体取决于您使用的托管环境.
If you want to restrict access to files, you should consider storing them outside the public DocumentRoot and using PHP to deliver the file, applying your own access logic. This means outside the www or public_html folders, depending on the hosting environment you are working with.
<?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);
}
相关文章