6

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;"
weblen
  • 149
  • 1
  • 2
  • 9

1 Answers1

15

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.

-- Edit Y2023 --

If you want the script to be prepared for 302 code (redirect) you will need to add the following headers

CURLOPT_FOLLOWLOCATION = true CURLOPT_MAXREDIRS = 10 // This is not mandatory (-1 By default).

Regards

manuelbcd
  • 3,106
  • 1
  • 26
  • 39
  • and if the url does a 302 redirect to another image url. what do we need to add to this? – Shaho Apr 28 '23 at 09:15
  • @Shaho I think it would require the flag CURLOPT_FOLLOWLOCATION = true and CURLOPT_MAXREDIRS higher than 0 the code would be similar excepting for those flags – manuelbcd May 09 '23 at 13:41