PHP文件强制下载

4
当我使用这段代码下载这张图片(仅用于测试目的),我打开下载的图片时,只会给我一个错误。我在chrome中尝试过。在使用windows照片查看器打开时,它说无法显示图片,因为它是空的?以下是代码:
<?PHP
 // Define the path to file
 $file = 'http://www.media.lonelyplanet.com/lpi/12553/12553-11/469x264.jpg';

 if(!file)
 {
     // File doesn't exist, output error
     die('file not found');
 }
 else
 {
     header('Content-Description: File Transfer');
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename='.basename($file));
        header('Content-Transfer-Encoding: binary');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Pragma: public');
        header('Content-Length: ' . filesize($file));
        ob_clean();
        flush();
        readfile($file);
        exit;
 }
 ?>

readfile函数能读取远程文件吗? - dm03514
尝试移除头部并查看是否出现错误。 - gosukiwi
当我尝试从我的网站下载图像时,我得到相同的错误。让我尝试删除头部。 - droidus
所以我移除了标题,得到了很多随机的ASCII字符。 - droidus
请注意,上述脚本还有另一个明显的问题:"if(!file)" 并没有检查文件是否存在,而是仅仅检查字符串是否存在。 - Raptor
4个回答

4

我已经有机会解决了这个问题。你的问题有两个方面。

首先,从url中删除www.

其次,删除对filesize($file)的调用,因为PHP在下载文件之前不知道文件的大小而引发错误。(实际上,只需删除整行即可)

删除这两个东西后,我成功了。


是的,filesize 应该仅在提供本地文件下载选项(服务器上的文件)时使用。 - Manu Manjunath

2

ob_clean()替换为ob_end_clean()

你仍在缓冲,因此没有任何图像内容传输到浏览器。


等一下,我没有看到你开始缓冲了...那个ob_clean到底是为什么呢? - Umbrella
你尝试将MIME类型正确设置为image/jpeg了吗? - Umbrella

1
如果您只是想在单击链接时从第三方下载文件,可以在锚标签中使用新属性“download”。
代码将类似于:
<a download href="path/to/the/download/file"> Clicking on this link will force download the file</a>

它适用于Firefox和Chrome的最新版本。我需要提醒一下,我没有在IE上进行测试。:P

1

替换:

ob_clean();
flush();
readfile($file);

使用:

echo file_get_contents($file);

仍然不起作用,顺便说一下,使用 header('Content-Type: image/jpeg');。 - droidus
哈。在您的URL字符串中去掉www. - iambriansreed
这个程序相关的内容翻译成中文:所以它应该像这样:http://media.lonelyplanet.com/lpi/12553/12553-11/469x264.jpg? 仍然不起作用 :p - droidus
错误版本仍然在缓存中吗? - GolezTrol
它被称为 file_get_contents() 而不是 get_file_contents - B001ᛦ
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接