使用php但创建空文件的卷曲图像

时间:2015-12-02 06:50:12

标签: php curl

我正在尝试使用他的代码来卷曲图像。但它适用于某些图像链接,但来自维基百科/维基媒体的图像无效。例如https://upload.wikimedia.org/wikipedia/commons/thumb/6/64/Johan_van_der_Veeken.jpg/266px-Johan_van_der_Veeken.jpg

代码:

<form method="post">
<input type="text" name="image_url">
<input type="submit">
</form>
<?php

if($_SERVER['REQUEST_METHOD'] == 'POST'){
 $image =$_POST["image_url"];
$path_parts = pathinfo($image);
$rename=$path_parts['filename'];
$extension=$path_parts['extension'];

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

$fp = fopen("dowloads/$rename.$extension",'w');
fwrite($fp, $rawdata);
fclose($fp);
echo "$rename.jpg";
}
?>

错误:
当我尝试在Windows照片查看器中打开文件时,它会显示can't display this picture because the file is empty.

1 个答案:

答案 0 :(得分:4)

由于您试图从http(s)链接中获取图像,因此您必须执行以下操作:

//Init curl
$ch = curl_init ($url);

//Required to be false
curl_setopt($ch, CURLOPT_HEADER, 0);

//Required for http(s)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

//Required to be true
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);

//Response data
$rawdata=curl_exec($ch);

//close
curl_close ($ch);

注意:这是一种非常糟糕的方法,可以忽略SSL警告。相反,您应该设置证书并下载,强制SSL(如果可用)