php限制访问目录中的文件 [英] php restrict access to files in directory

查看:95
本文介绍了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限制访问目录中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆