如何防止直接访问文档


How to prevent documents from direct access

嗨,我们有一个带有php文档存储库的Web应用程序,Web服务器是apache。如何防止直接使用 url 访问这些文档文件,以便只有我们的用户才能在登录后访问文档。用于访问文档的 URL 也显示在谷歌搜索结果中。

不要将文件存储在 Web 根目录中。将它们保留在您的 Web 根目录之外,并通过 PHP 文件引用它们。该文件将对用户进行身份验证,以验证您是否希望他们能够下载该文件并允许他们查看该文件。否则,它将阻止发生或加载错误消息。

.HTML:

<a href="download.php">Download</a>

PHP示例(下载.php):

<?php
    if (!isset($_SESSION['authenticated']))
    {
        exit;
    }
    $file = '/path/to/file/outside/www/secret.pdf';
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename=' . basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;
?>