从URL保存图像与cURL
问题描述:
我需要将图像从url直接保存到我的服务器,我已经尝试了很多方法,但似乎都无法正常工作。 file_put_contents($file_location, file_get_contents($image_url));
让我没有找到文件目录找到错误。简单的fopen
和fwrite
不断返回损坏的图像。这一个工作,但它不断返回HTML文件,而不是JPG文件。从URL保存图像与cURL
function getimg($url) {
$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
$headers[] = 'Connection: Keep-Alive';
$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
$user_agent = 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)';
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
$imgurl = 'http://some/url/to/image.jpg';
$imagename= basename($imgurl);
if(file_exists('./image/'.$imagename)){continue;}
$image = getimg($imgurl);
file_put_contents('image/'.$imagename,$image);
东西不见了?
谢谢。
答
你的代码工作正确。它从给定的URL下载图像。
你的问题将在图像存储的路径。
if(file_exists('./image/'.$imagename)){continue;}
$image = getimg($imgurl);
file_put_contents('image/'.$imagename,$image);
在上面的代码检查./image/并给予路径作为file_put_contents路径的路径。
+0
对不起,我找到了解决方案,URL(图像名称)有'空间'字符,所以我必须用'%20'替换它们。感谢您的回复。 – Hebbian
答
此方法效果:
<?php
file_put_contents("/var/www/test/test.png", file_get_contents("http://www.google.com/intl/en_com/images/srpr/logo3w.png"));
?>
您需要启用allow_url_fopen
,它是最简单的方法。见http://php.net/manual/en/features.remote-files.php
你确定这是一个你想下载的图像文件,而不是一个网页?你得到的HTML文件包含什么? – JJJ