PHP强制下载损坏的PDF文件

PHP强制下载损坏的PDF文件,php,file,pdf,Php,File,Pdf,我已经阅读了所有关于堆栈溢出的文章,无法修复我的问题。我正在使用以下代码: $file = $_GET['url']; header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename="'.basename($file).'"'); header('Content-Length: ' . filesize($file)); readfile($file); e

我已经阅读了所有关于堆栈溢出的文章,无法修复我的问题。我正在使用以下代码:

$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,而不是原始大小。$\u GET['url']正在接收其中的
。/dir/dir/filename.pdf
。文件名也是其中的空格。出于安全原因,我无法共享文件名


请告诉我哪里出了问题。

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

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

我希望这对你有帮助

为了进一步扩展,我还用application/pdf替换了application/octet stream。问题是“PHP(如何)强制下载损坏的pdf文件”,但在你的问题中,你说:“上面提到的代码正在下载文件”-那么问题出在哪里?上面的代码正在下载损坏的文件。当我检查PDF文件的大小时,它是1KB。很抱歉标题混淆。请在第一行之后添加此代码,然后重试
echo'IS FILE:'。(is_file($file)?“YES!”:“NO:(”)。”
-你看到了什么?这是你的问题-你必须提供一个有效的文件名。只是文件存在问题…甚至没有输入if。我的路径/url应该是什么?应该是http的全部内容吗?还是将使用“./dir/dir/filename.pdf”够了吗?你需要找到文件的位置,否则你将一无所获。是的,你可以使用相对路径,但它必须与正在执行的脚本的位置相对应。最好找到完整路径,并使用上面的代码填充到
$file\u base\u path
中。呜呼…好了,现在下载文件了正确,但唯一的问题是它不是以.pdf扩展名下载的。我可以用openwith打开下载的文件…文件\u base\u路径技巧奏效。我如何使它以.pdf扩展名下载文件?我是否将内容类型更改为application/pdf?同样,在上面第4行的代码中,我认为我们不需要这一行。@syedmammadKazmi-非常好!请尝试使用:
Content Disposition='attachment;filename='.basename($file)。.pdf'
@SyedMHammadKazmi-如果这已经解决了您的问题,请将我的答案标记为已接受答案并进行投票。谢谢!
$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>";