保护文件免受直接HTTP请求的影响

时间:2012-07-07 13:41:41

标签: php security httprequest

假设您的网络服务器上托管了大量文档,但您不希望通过直接HTTP请求检索它们,因为这些文件是保密的。我们开始加密文件名,但是我们希望它更进一步,那么将这些文件放在/ public_html文件夹之外并让PHP从/ public_html之外的文件夹中检索所请求的文件呢?

我正在尝试测试这个但是我的小脚本正在检索一个文件名错误的0kb .pdf文件:

<?php 

$file = '/home/clientaccount/secretfiles/file.pdf'; 
if(!file_exists($file)){
    die('Error: File not found.');
}
else
{
    // Set headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/pdf");
    header("Content-Transfer-Encoding: binary");
} ?>

3 个答案:

答案 0 :(得分:2)

变量$ file只是一个字符串。到达访问者的标题告诉:

  

内容 - 处置:附件;   文件名= /家庭/ clientaccount / secretfiles / file.pdf

这不是访问者可以访问的文件夹。

答案 1 :(得分:1)

你必须在if中使用许多右括号:

if(!file_exists($file)){

这可能是服务器错误的原因,如果运行服务器的用户可以访问外部位置,则代码应该可以正常工作。

答案 2 :(得分:1)

为了使你的代码正常工作,我不得不添加一个命令让php读取文件并输出:

<?php 

$file = '/tmp/file.pdf'; 
if(!file_exists($file)){
    die('Error: File not found: '.$file);
}
else
{

    // Set headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/pdf");
    header("Content-Transfer-Encoding: binary");
    readfile($file);
} 

?>

否则我下载后无法读取文件。

正如Hans Kuit所说,最好从文件名中删除路径。

相关问题