This has been asked before, but most, if not all answers, were either solutions that didn't work in all situations or were unnecessary (like using getimagesize()
, which downloads the entire image).
How would I check if a given URL leads to an image without having to hardcode image extensions (like .png
', .jpg
, etc.)?
You can read only file header by CURL and then detect if the header is image header or not.
curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $file_url);
curl_setopt($curl, CURLOPT_NOBODY, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$header = curl_exec($curl);
curl_close($curl);
if (strstr($header, 'image/png')) {
//file is image
}