我一直在搜索互联网以及来自SO的许多帖子并且没有运气。我有以下代码从远程服务器获取文件。
$url = 'http://www.example.com/images/abc.png';
$path = '/home/axxxxxxx/public_html/images/abc.png';
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
curl_close($ch);
fclose($fp);
$url
和$path
表示来自一台服务器的文件。当我运行代码时,html页面会输出一个以 ‰PNG IHDRàw=ø IDATxÚ•yLWÇ¿3³3³ì² (VP)àUÓzDc«
开头的奇怪代码....
当我使用文本编辑器打开new.png时,我得到的代码与上面的php cURL脚本所在页面中的代码相同。 (这似乎是脚本读取的正确文件)
我也收到错误消息,
Warning: fopen(../axxxxxxx/public_html/images/new.png) [function.fopen]: failed to open stream: No such file or directory in /home/ayyyyyyy/public_html/test.php on line 5
Warning: curl_setopt(): supplied argument is not a valid File-Handle resource in /home/ayyyyyyy/public_html/test.php on line 8
此处显示的unicode字符集( PNG IHDRàw=ø IDATxÚ•yLWÇ¿3³3³ì² (VP)àUÓzDc«
)
Warning: fclose(): supplied argument is not a valid stream resource in /home/ayyyyyyy/public_html/test.php on line 12
如果重要的话,这两个网站都在000webhost.com上托管。
如何将文件下载到用户的计算机上?
答案 0 :(得分:0)
问题是(如果有的话)是您正在下载的文件是PNG
文件而您正试图将其作为文本文件读取 - 这是您看到的“奇怪代码”
如果您在将文件输出到浏览器之前发送了Content-Type
标题,您将看到实际图像:
header('Content-Type: image/png');
echo $data;
按download the file to the user's computer
,我假设您要提示用户下载文件。为此,请将Content-disposition
标头设置为attachment
。您也可以将它与上面的内容类型标题结合起来:
header("Content-Type: image/png");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"some_image.png\"");