阻止在PHP安全网站上直接访问PDF

时间:2015-04-06 11:00:05

标签: php .htaccess

我使用登录创建了一个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>

我该怎么办?

2 个答案:

答案 0 :(得分:0)

您可以在阻止列表中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标头。

答案 1 :(得分:0)

如果您只希望只有登录用户才能下载pdf文件: 在您的html页面中,您放置了以下链接,例如:

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

然后创建一个如下所示的php文件:

download.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;
    }
}
?>