0

假设您有一堆文档托管在您的网络服务器上,但您不希望通过直接 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");
} ?>
4

3 回答 3

2

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

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

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

于 2012-07-07T13:59:33.367 回答
1

你必须在 if 中有很多右括号,应该是:

if(!file_exists($file)){

这可能是服务器错误的原因,并且您的代码应该可以工作,前提是运行服务器的用户可以访问外部位置。

于 2012-07-07T13:55:04.063 回答
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 所说,最好从文件名中删除路径。

于 2012-07-07T14:22:57.237 回答