php restrict access to files in directory(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);
}
这篇关于php限制对目录中文件的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:php限制对目录中文件的访问


基础教程推荐
- Web 服务器如何处理请求? 2021-01-01
- php中的foreach复选框POST 2021-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php中的PDF导出 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01