Verifying Image Existence at Remote URLs with PHP
In the realm of dynamic image generation, the ability to verify the existence of images at remote URLs is crucial. While numerous approaches employing PHP libraries and external tools exist, their reliability and performance often leave much to be desired. For efficient and expedient image existence checks, a robust solution is necessary.
Fortunately, the PHP curl library offers an optimized solution. The following code demonstrates a highly performant function leveraging curl to determine image availability:
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
// Only request headers, don't download the entire content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result !== FALSE;
}
By utilizing CURLOPT_NOBODY, this function omits content download, significantly reducing execution time. Additionally, CURLOPT_FAILONERROR ensures that any HTTP error codes trigger a FALSE return value. The CURLOPT_RETURNTRANSFER option captures the HTTP header response, allowing the function to ascertain image existence without the overhead of downloading the entire image file.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3