使用 cURL 从 URL 保存图像到服务器会导致空白图像

Saving and image to server from a URL using cURL results in a blank image

$camera_ip = "10.10.10.10";

$image_url = "http://$camera_ip/cgi-bin/image.jpg?camera=right&size=1024x768&quality=60";

$ch = curl_init($image_url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$rawdata = curl_exec($ch);
curl_close($ch);

$fp = fopen('./logo.jpg', 'wb');
fwrite($fp, $rawdata);
fclose($fp);

文件正在 7KB 保存,但大小为 0x0 ...我不明白为什么文件没有被正确保存。我的猜测是文件在保存之前没有完全加载,但有没有办法确保这一点?

尝试使用 "w" 而不是 "wb" $fp = fopen('./logo.jpg', 'w'); 或者尝试:file_put_contents('./logo.jpg',$rawdata);(不确定它是二进制安全的,应该是)

检查你的卷曲结果,看看返回了什么。

$info = var_export(curl_getinfo($ch),true);
file_put_contents('log.txt',$info);

header('content-type: text/plain');
var_export(curl_getinfo($ch));

更新

curl 请求失败(返回 false)。
现在你需要找出原因。

现在改变你的:

curl_setopt($ch, CURLOPT_HEADER, 0);

收件人:

curl_setopt($ch, CURLINFO_HEADER_OUT, true);

添加这些选项以解决问题:

curl_setopt($ch, CURLOPT_ENCODING,"");   
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT,10);
curl_setopt($ch, CURLOPT_FAILONERROR,true);
curl_setopt($ch, CURLOPT_VERBOSE, true);

$data = curl_exec($ch);
if (curl_errno($ch)){
    echo ' Retrieve Base Page Error: ' . curl_error($ch);
}
else {
  $info = rawurldecode(var_export(curl_getinfo($ch),true));
  $skip = intval(curl_getinfo($ch, CURLINFO_HEADER_SIZE)); 
  $responseHeader= substr($data,0,$skip);
  $data= substr($data,$skip);
  echo "HEADER: $responseHeader\n";
  echo "\n\nINFO: $info\n\nDATA: $data";
}  

您可能会得到 "Retrieve Base Page Error:",但它也会告诉您失败的原因。如果无法回显,请将 echo 替换为 $info .=