【问题标题】:php restrict access to files in directoryphp限制对目录中文件的访问
【发布时间】:2013-10-28 21:15:04
【问题描述】:

我试图限制对目录中文件的直接访问。所以例如我有 website.com/files/example.flv.

所以如果用户直接访问 URL 中的文件,我希望他们被重定向到主页。

我使用 htaccess 尝试了以下操作

deny from all

但它不是很好用。有没有办法我可以使用 php 做到这一点,然后在用户直接进入 url 中的文件时,他们将被重定向。

因此,如果用户转到 url 中的文件链接,他们将被发送到主页。那么这只能使用htaccess来完成

【问题讨论】:

  • 在您的文件夹中创建一个 index.php。 Apache 在你的文件夹中执行 index.php。在您的 index.php 中,您可以使用 header() 函数重定向到另一个页面
  • 这是非常不安全的,因为文件本身仍然可以访问。

标签: php file download


【解决方案1】:

如果你想限制对文件的访问,你应该考虑将它们存储在公共 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);
}

【讨论】:

  • 感谢这有助于加载。我不知道你可以在 public_html 之外保存文件
【解决方案2】:

是的。您必须将文件放在无法通过网络访问的目录中。然后,您必须在 public_html/files/ 文件夹中创建一个 .htaccess 文件,该文件指向您的 php 脚本。

类似这样的东西(注意:代码未经测试):

结构:

  • 根/
    • 真实文件/
    • public_html/
      • 文件/
        • .htaccess
      • filehandler.php

.htaccess:

RewriteEngine on
RewriteRule ^/files/(.+)$ filehandler.php?stuff=$1 [QSA]

文件处理程序.php:

header('Location: /');

当然,当您希望文件访问它们时,您会希望它们可以被访问。这可以在 filehandler.php 中完成,方法是检查是否允许用户查看文件,然后返回如下内容:

header('Content-type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename(urlencode($file['name'])).'"');
readfile($dir.basename($file['filename']));
exit;

【讨论】:

  • 如果文件非常大,您需要小心这一点,因为您可能很快就会耗尽内存。
  • 谢谢,但是如果文件名在目录之外,您将如何获取文件名?
  • @DanielLematy 我已经更新了答案(参见 .htaccess, ?stuff=$1)。 $_GET['stuff'] 现在包含文件名/请求。
猜你喜欢
  • 2016-08-20
  • 2013-01-04
  • 1970-01-01
  • 2011-12-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
相关资源
最近更新 更多