只允许从php脚本访问Apache 2.4目录-如何?

xoshrz7s  于 2023-05-05  发布在  PHP
关注(0)|答案(2)|浏览(161)

我有一个Windows Apache Web服务器,它有一个Map到我的Linux映像服务器的驱动器。Linux映像有一个目录,将pdf文件存储在我们通过PHP脚本访问的某个目录中。在我的httpd.conf文件中,我们有一个别名设置,它允许使用Require All granted访问这个目录。问题是,我们最近发现,如果一个人知道文档的名称,他们可以在Web浏览器中输入我们的domain.com/<directory>/nameofdocument.pdf,然后访问我们的成像服务器上的pdf文档。当然,他们必须知道文件的确切名称,包括它存储在哪个目录中才能调出pdf文件。这是一个我们不允许的安全漏洞。我不希望一个人能够输入我们的服务器地址在地址栏和拉一个文件的方式。我们的php脚本访问该目录,用户可以点击链接来拉出文档。
换句话说,我只希望能够允许一个人查看PDF,如果他们登录到我们的机构系统(这是一个PHP编写的系统),他们通过我们的成像PHP脚本访问。这可能吗?
这就是我的<directory>指令的样子。

Alias /ourdocs/ "Z:/documents/"
<Directory "Z:/documents">
    Options none
    AllowOverride all
    Require all granted
</Directory>
xytpbqjk

xytpbqjk1#

为了阻止“外部”访问文件或目录是,您可以使用所示指令的修改

<Directory "Z:/documents">
  Require local
  Require ip 172.16.0.10
  Require ip 192.168.1.0/24
  Require all denied
</Directory>

在本例中,只有“localhost”(Web服务器本身)、IP为www.example.com的机器172.16.0.10以及子网www.example.com中的任何机器192.168.1.0/24可以通过Web直接访问此目录。
编辑,由于(不必要的?)洞察PHP端
现在,除了写入的IP之外,所有的目录访问都被禁用。为了下载文件,在您当前拥有文件直接链接的页面上(例如:<a href="domain.com/<directory>/nameofdocument.pdf">),则需要将其替换为类似<a href="domain.com/fileManager.php?fileId=32">的内容
32当然是例如存储可用文件的数据的表中的文件的id。
在您的fileManager.php页面中,您将需要有如下内容

// Other stuffs
....
// Check if the user is logged in
$logged_in = $this->isLoggedIn();
if ($logged_in) {
    // Ok, the user is logged in
    // Go to retrieve the path for the requested file id
    $file = $this->docDb->findDocument( intval( $_GET [ "fileId" ] ) );
    // Does the file exists?
    if (file_exists( $file )) {
        // Here we are, the file exists. Force the download
        header( 'Content-Description: File Transfer' );
        header( 'Content-Type: application/octet-stream' );
        header( 'Content-Disposition: attachment; filename="' . basename( $file ) . '"' );
        header('Expires: 0' );
        header( 'Cache-Control: must-revalidate' );
        header( 'Pragma: public' );
        header( 'Content-Length: ' . filesize( $file ) );
        readfile( $file );
        // Exit or do other things, it depends on your purpose after downloading the file
        exit();
    } else {
        // Nope, the file doesn't exists
        $this->error( "Sorry, the requested file does not seem to exist" );
    }
} else {
    // Nope, the user isn't logged in
    $this->error( "Sorry, you're not authorized to download the file" );
}
// Other stuffs
....
jutyujz0

jutyujz02#

将documents文件夹放在网站之外,在Apache中没有为它配置目录。然后有一个getDocument.php脚本,当传递合适的文档ID(例如也许你的数据库中有存储的文档?),首先检查用户是否具有有效的登录会话,如果是,则使用readFile()将文件输出到客户端(当然,还要设置适当的头,以便它作为下载出现)。
这样,对文件的唯一访问是通过一个脚本,该脚本首先验证您的状态。直接链接将不起作用,因为没有直接的HTTP路由到文件本身。

相关问题