gpt4 book ai didi

php限制对目录中文件的访问

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:00:58 25 4
gpt4 key购买 nike

我正在尝试限制对目录中文件的直接访问。所以例如我有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);
}

关于php限制对目录中文件的访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19645196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com