Check If Remote Images Exist Php
Solution 1:
You can use getimagesize
since you are dealing with images it would also return mime type of the image
$imageInfo = @getimagesize("http://www.remoteserver.com/image.jpg");
You can also use CURL to check HTTP response code of am image
or any URL
$ch = curl_init("http://www.remoteserver.com/image.jpg");
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 2);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_exec($ch);
if(curl_getinfo($ch, CURLINFO_HTTP_CODE) == 200)
{
// Found Image
}
curl_close($ch);
Solution 2:
Depending on the number of images and frequency of failures, it's probably best to stick with your current client-side approach. Also, it looks like the images are served through Amazon CloudFront - in that case, use the client-side approach because it could just be a propagation issue with a single edge server.
Applying server-side approach will be network intensive and slow (waste of resources), especially in php because you'll need to check each image sequentially.
Solution 3:
Also might be useful check the request headers, using get_headers php function as follows:
$url = "http://www.remoteserver.com/image.jpg";
$imgHeaders = @get_headers( str_replace(" ", "%20", $url) )[0];
if( $imgHeaders == 'HTTP/1.1 200 Ok' ) {
//img exist
}
elseif( $imgHeaders == 'HTTP/1.1 404 Not Found' ) {
//img doesn't exist
}
Solution 4:
The following function will try to get any online resource (IMG, PDF, etc.) given by URL using get_headers
, read headers and searching for string 'Not Found' in it using function strpos
. If this string is found, meaning the resource given by URL is not available, this function will return FALSE, otherwise TRUE.
functionisResourceAvaiable($url)
{
return !strpos(@get_headers($url)[0],'Not Found')>0;
}
Post a Comment for "Check If Remote Images Exist Php"