php文件强制下载错误

时间:2012-03-31 01:40:29

标签: file

我正试图强制下载。这是我的代码:

 <?PHP
 // Define the path to file
 $file = 'http://myimage.com/users/test/uploads/1234.png';

 if(!file)
 {
     // File doesn't exist, output error
     die('file not found');
 }
 else
 {
     header('Content-disposition: attachment; filename='.$file);
    header('Content-type: application/octet-stream');
    readfile($file);
}
?>

这是我在firefox中遇到的错误:“图像”文件:/// C:/ Users / Username / Downloads / 1234%20(4).png“因为包含错误而无法显示。” %20(4)是一个空格,可能是我尝试下载的第四个副本。

2 个答案:

答案 0 :(得分:1)

您的Content-Type错了。迫使下载所需的只是Content-Disposition: attachment;将其更改为image/png而不是application/octet-stream

此外,您在打开<?php标记之前有一个空格。你需要把它拿出来。

此外,您的“文件存在”检查不会按照您的想法执行。使用file_exists检查文件是否存在,并记住$符号。

答案 1 :(得分:0)

确保<?php ?>标记之外没有任何空行。

相关问题