【问题标题】:Prevent direct access to a PDF on a PHP secured website防止在 PHP 安全网站上直接访问 PDF
【发布时间】:2015-04-06 11:00:05
【问题描述】:

我创建了一个带有登录名的 PHP 网站,用户可以访问 PDF 文件。 如何防止未经授权的用户通过直接链接访问 PDF 文件?

我尝试使用 .htaccess,但“拒绝所有来自 localhost 的允许”也阻止了我的登录用户。我尝试使用 RewriteEngine,即使我删除带有空引用者的行,它也允许所有内容:

# ultimate hotlink protection
<IfModule mod_rewrite.c>
 RewriteEngine on
 RewriteCond %{HTTP_REFERER}     !^$
 RewriteCond %{REQUEST_FILENAME} -f
 RewriteCond %{REQUEST_FILENAME} \.(gif|jpe?g?|png)$           [NC]
 RewriteCond %{HTTP_REFERER}     !^https?://([^.]+\.)?domain\. [NC]
 RewriteRule \.(gif|jpe?g?|png)$                             - [F,NC,L]
</ifModule>

我能做什么?

【问题讨论】:

    标签: php .htaccess


    【解决方案1】:

    你可以pdf在你的屏蔽列表中:

    # ultimate hotlink protection
    <IfModule mod_rewrite.c>
     RewriteEngine on
     RewriteCond %{HTTP_REFERER}     !^$
     RewriteCond %{REQUEST_FILENAME} -f
     RewriteCond %{HTTP_REFERER}     !^https?://([^.]+\.)?domain\. [NC]
     RewriteRule \.(gif|jpe?g?|png|pdf)$ - [F,NC,L]
    </ifModule>
    

    但请记住,基于 HTTP_REFERER 的阻止并非 100% 安全,因为客户端也可以发送自定义 HTTP_REFERER 标头。

    【讨论】:

    • 我在本地列表中添加了pdf,我只是从源代码复制粘贴,它不起作用。为了保护这些文件,我还有哪些其他选择?
    • 其他选项是将pdf文件保留在DocumentRoot之外并从您的PHP代码中读取pdf内容。
    • 如果可能,我想将文档保留在原处,并使用 htaccess 只允许来自“domain/document_access.php?id=something”的用户这可能吗?
    • 该解决方案已经存在,您需要解释为什么它不适合您。
    【解决方案2】:

    如果您想要的只是只有登录用户可以下载 pdf 文件: 在您的 html 页面中,您放置了例如此链接:

    <a href:'download.php'>Download now!</a>
    

    然后像这样创建一个php文件:

    下载.php

    <?php 
    session_start();
    if(!isset($_SESSION["IdUser"])) {
        header("location:goToHell.php");
    } 
    else {
        $file="yourPath/theFile.pdf";
    
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/pdf');
            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;
        }
    }
    ?>
    

    【讨论】:

      猜你喜欢
      • 2012-09-16
      • 1970-01-01
      • 2016-10-09
      • 1970-01-01
      • 1970-01-01
      • 2010-11-05
      • 2010-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多