是否可以仅使用 PHP/HTML 从受保护的目录中读取


Is it possible to read from protected directory using only PHP/HTML?

我有一个目录,其中包含的数据在某个日期之前不应该被世界访问。

当然,该目录不应使用 Web 浏览器直接全局可读。 我目前使用 .htpasswd 和 .htaccess 解决这个问题。

但是,有一个全局可读的.php文件,一个目录级别更高。 PHP 文件基于日期,有条件地生成从受保护目录中读取的基本 HTML 标记(例如,<img .../>)。

不幸的是,在我的测试中,.php文件需要身份验证才能加载数据。 我的问题是我是否在尝试做一些根本上不可能的事情,或者我是否可以调整它以使其工作。 另外,如果可能,我是否应该了解任何其他问题(安全性或其他问题)?

附加信息:

  • 如果可能的话,我宁愿不使用Javascript。
  • PHP 5.3 可用。
  • 还有其他解决方案的想法(我已经想到了一个cron工作,我可能还会这样做)?

我猜你可能遇到的一个问题是,如果你尝试输出<img src="protected.jpg" />,即使是从一个不受保护的php文件,你也能显示HTML,但不能显示图像文件本身。

如果我正确理解您要做什么,则需要:

  • 用 PHP 编写某种代理脚本,以控制对每个文件的访问(这有点乏味,需要生成正确的标头 + MIME 类型)。
  • 使用时间/日期条件直接从 .htaccess 控制访问,这可能是您的最佳选择。 看那里 : http://www.askapache.com/htaccess/time_hour-rewritecond-time.html

编辑:代理示例:我似乎无法在网上找到示例,因此当我希望控制从PHP访问文件时,这是我经常使用的功能(例如,这可能是敏感数据,其访问权限需要从$ _SESSION或DB值进行验证):

function send_binary_data($path, $mimetype, $filename = null){
    @ob_clean();
    if($filename === null) $filename = basename($path);
    $size = filesize($path);
    //no-cache
    header('Cache-Control: no-cache, must-revalidate, public');
    header('Pragma: no-cache');
    //binary file
    header('Content-Transfer-Encoding: binary');
        //mimetype
    header('Content-Type: ' . $mimetype);
    header('Content-Length: ' . $size);
    header('Content-Disposition: inline; filename=' . $filename);
    header('Content-Description: ' . $filename);
    $chunksize = 1 * (1024 * 1024);
    $buffer = '';
    $handle = fopen($path, 'rb');
    if ($handle === false) {
        return false;
    }
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        print $buffer;
    }
    $result = fclose($handle);
    unset($handle);
    $handle = null;
    die();
}   

当然,您仍然需要限制从.htaccess的直接访问,但是对于代理,您将所有请求重定向到未受保护的代理脚本,如下所示:

RewriteEngine ON
RewriteRule ^(.*)$ /proxy.php?file=$1 [NC,QSA]

代理.php将包含类似以下内容:

if(!isset($_GET['file'])) die('file not set');
$file = $_GET['file'];
//perform all your custom checking, including security checks due to retrieving data from $_GET, and if access is granted :
$path = 'yourpath/'.$file;
$mimetype = 'defineregardingyour/ownrules';
send_binary_data($path, $mimetype); 
.

htaccess仅用作直接从Internet到目录的访问控制。

PHP 访问由 chmod 权限控制。尝试将其修改为 755。您仍然可以使用 .htaccess 文件对其进行密码保护或任何其他类型的保护。

考虑到添加的注释,我假设您正在尝试在输出中包含受保护目录中的图像。当然,未经身份验证的用户无法访问它们...否则你为什么要保护他们?

您可以将需要全球可访问的文件添加到您的 .htaccess 文件中。