【发布时间】:2013-04-03 14:46:12
【问题描述】:
我整天都在寻找这个问题的答案,但没有运气!
我想将图像从网络下载/复制到我服务器上的某个位置,下面的代码不会引发任何错误,除了图像只是没有保存到所需的目录或任何目录。
如您所见,我正在使用 cURL 获取图像并且变量 $contents 返回 true (1),因此我假设脚本有效,但实际上我遗漏了一些东西。
非常感谢您的帮助。 :-)
$dir = URL::base() . "/img/products/";
$imgSrc = "an image on the web";
$file = fopen($dir, "wb");
$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)';
$ch = curl_init($imgSrc);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FILE, $file); // location to write to
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
$contents = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
curl_close($ch);
fclose($lfile);
if ($curl_errno > 0)
{
Log::write("CURL", "cURL Error (".$curl_errno."): ".$curl_error);
}
else
{
Log::write("CURL", "Data received: " . $contents);
}
return;
【问题讨论】:
-
您没有指定正确的文件名... $dir 中仅存在目录路径。
-
感谢您的回复我改成这个:$file = fopen($dir .basename($imgSrc), "wb");但我得到了相同的结果。
-
改成绝对路径:$file = fopen("domain.co.uk/img/products/newfilename.jpg", "wb");仍然得到相同的结果。