php 在php中下载图片代码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14745232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Download image code in php
提问by Shahbaz Pothiawala
I am a newbie to php and wish to write a code for download that allows users to download image. Meaning i have given a download link onclick of whick the image located on the server should start downloading. i have tried various options like fopen, curl etc. but to no avail. on using curl the image downloads but does not open up in the place where it gets downloaded. It gives error saying "Cant read file header! unknown file format." Please help here's the curl code i used :
我是 php 的新手,希望编写一个允许用户下载图像的下载代码。这意味着我已经给了一个下载链接,点击位于服务器上的图像应该开始下载。我尝试了各种选项,如 fopen、curl 等,但无济于事。使用 curl 会下载图像,但不会在下载位置打开。它给出了“无法读取文件头!未知文件格式”的错误消息。请帮助这是我使用的 curl 代码:
function DownloadImageFromUrl($imagepath)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_POST, 0);
curl_setopt($ch,CURLOPT_URL, $imagepath);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
curl_close($ch);
return $result;
}
$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'w');
fwrite($savefile, $imagecontent);
fclose($savefile);
回答by Vadim
You should use http headers for this
您应该为此使用 http 标头
header('Content-Type: "'.$mime.'"');
header('Content-Disposition: attachment; filename="'.$filename.'"');
header("Content-Transfer-Encoding: binary");
header('Expires: 0');
header('Pragma: no-cache');
header("Content-Length: ".strlen($data));
exit($data);
mime - MIME type of image
mime - MIME 类型的图像
filename - Name of downloading file
文件名 - 下载文件的名称
data - the file. You can get image from other server using for example this:
数据 - 文件。您可以使用例如以下方法从其他服务器获取图像:
$data = file_get_contents('http://www.xyz.com/back_img.png')
回答by Faizan Khattak
Try This
尝试这个
$imagecontent =DownloadImageFromUrl("http://www.xyz.com/back_img.png");
$savefile = fopen('myimage.png', 'r');
fread($savefile, $imagecontent);
fclose($savefile);
回答by swapnesh
You need to add header()method to make it open as a downloadable item.
您需要添加header()方法以使其作为可下载项目打开。
header("Content-Type: application/force-download");
header("Content-Disposition: attachment; filename=\"".basename($fullPath)."\";" );
where
在哪里
$fullPathis the image path.
$fullPath是图像路径。
For more specification refer to - header in php
有关更多规范,请参阅 - php 中的标头
回答by Muhammed
function downloadFile ($url, $path) {
$newfname = $path;
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
downloadFile ("http://www.site.com/image.jpg", "images/name.jpg");

