PHP强制下载损坏的PDF文件

时间:2016-07-07 08:54:08

标签: php file pdf

我已经浏览了Stack Overflow上的所有文章,无法解决我的问题。我使用以下代码:

$file = $_GET['url'];
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($file).'"'); 
header('Content-Length: ' . filesize($file));
readfile($file);
exit;

上面提到的代码是从根目录正上方下载文件,是的是下载PDF文件,但文件大小只有1KB而不是原始大小。 $ _GET ['url']正在接收../dir/dir/filename.pdf。文件名也是空格。出于安全原因,我无法共享文件名。

请告诉我哪里出错了。

1 个答案:

答案 0 :(得分:1)

请确保您使用Web服务器路径访问该文件 - 例如您的路径可能是:/home/yourusername/public/sitename/downloads/<filename>,您应首先检查 - 以帮助您在PHP脚本的顶部运行此命令找出当前脚本的完整路径:

echo '<pre>FILE PATH: '.print_r(__FILE__, true).'</pre>';
die();

仅使用urlencode()使用网址发送文件名,并在接收PHP脚本上使用urldecode()来处理任何字符编码问题。

见这里:http://php.net/manual/en/function.urlencode.php 在这里:http://php.net/manual/en/function.urldecode.php

所以你在哪里创建你的网址:

<a href="/my-download-url/<?= urlencode('file name.pdf') ?>">Download File</a>

在你的php脚本中:

$file_base_path = '/home/yourusername/public/sitename/downloads/';
$file = urldecode($_GET['url']);
$file = $file_base_path . $file;
$file = $_GET['url'];
if (file_exists($file))
{
    if (FALSE!== ($handler = fopen($file, 'r')))
    {
        header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: chunked'); //changed to chunked
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        //header('Content-Length: ' . filesize($file)); //Remove

        //Send the content in chunks
        while(false !== ($chunk = fread($handler,4096)))
        {
            echo $chunk;
        }
    }
    exit;
}
echo "<h1>Content error</h1><p>The file does not exist!</p>";

我希望这可以帮到你!