Issue
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;"
Solution
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
Answered By - manuelbcd Answer Checked By - Mildred Charles (WPSolving Admin)