2015-11-20 87 views
2

我写了一个小的下载脚本来隐藏文件路径,文件“get_file.php”处理一切。 下一步我想禁止htaccess通过浏览器直接访问所有PDF文件(如果有人知道文件的确切URL),但仍然可以通过我的“get_file.php”访问文件。htaccess:不允许所有的pdf文件,但允许从PHP脚本(文件下载脚本)

我想:

RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(pdf)$ - [F] 

什么想法?

回答

4

在您的.htaccess的顶部试试这个规则:

RewriteEngine on 

RewriteCond %{THE_REQUEST} \.pdf[?\s] [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteRule^- [F] 
+1

打败了我。我曾经做过类似的回答,但是当我看到你的回答时清除了所有的东西 – starkeen

2

就试试这个:

get_file.php

<?php 
    // You can add extra codes to get your pdf file name here 
    $file = 'file.pdf'; 

    if (file_exists($file)) { 
     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; 
    } 
?> 
1

第一步 - htaccess的 - 有不同的方式我通常使用FilesMatch:

<FilesMatch "\.pdf$"> 
    Order allow,deny 
    Deny from all 
</FilesMatch> 

第二步是在你的PHP文件 - 你刚才使用本地路径来加载它,并显示它.. /path/to/file.pdf 下面举例说明如何将其导出为客户:correct PHP headers for pdf file download

相关问题