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限制对目录中文件的访问


基础教程推荐
- 如何替换eregi() 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01