Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get image from curl [duplicate]

Tags:

php

curl

My script works well except for the url in the code. I always get a 404. Of course I can get the image from browser. Could anybody help me fix this? PS:Actually, I could use method int "questions/6476212" to get the image file. But when trying to open the image file, the content in the file is a 404 page not the image.

$url = 'https://spthumbnails.5min.com/10368406/518420256_c_570_411.jpg';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
$res = curl_exec($ch);
$rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
curl_close($ch) ;
echo $res;"
like image 885
weblen Avatar asked Dec 20 '22 08:12

weblen


1 Answers

Your script is correctly written. I have tried and works fine, but you need to set image headers in order to let navigator show the image.

Example:

header("Content-Type: image/jpeg");

$url = 'https://images.nga.gov/en/web_images/constable.jpg';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
$res = curl_exec($ch);
$rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE); 
curl_close($ch) ;
echo $res;

But please note your image url is down, that's why you are getting 404 error.

Regards

like image 83
manuelbcd Avatar answered Dec 24 '22 01:12

manuelbcd