If downloading images using PHP the first step in avoiding errors is ensuring that the URL is valid. A great method for this is to check the URL HTTP response code.
200 means “ok” and the URL is valid and has not changed.
403, 404, 302 and 301 are the several main HTTP codes to seek when checking that the URL no longer contains what it should do.
Using exif_imagetype() as a request method gives the option to also confirm what type of image the content truly is. Then checking for key in the string of the HTTP response header.
$image_url = 'https://i.redd.it/fnxbn804hpd31.jpg'; $image_type_check = @exif_imagetype($image_url);//Get image type + check if exists if (strpos($http_response_header[0], "403") || strpos($http_response_header[0], "404") || strpos($http_response_header[0], "302") || strpos($http_response_header[0], "301")) { echo "403/404/302/301<br>"; } else { echo "image exists<br>"; }
The image is taken from Reddit, running the above code (as of this being posted) simply returns “image exists” because the URL is a HTTP response of 200.
If I changed the URL and added some random characters onto it chances are it is not a valid URL and returns “403/404/302/301”.
Another method is to check only for response 200:
$image_url = 'https://i.redd.it/fnxbn804hpd31.jpg'; $image_type_check = @exif_imagetype($image_url); if (strpos($http_response_header[0], "200")) { echo "image exists<br>"; } else { echo "image DOES NOT exist<br>"; }
Continuing on with the image EXIF type, you can run checks like:
if ($image_type_check == IMAGETYPE_JPEG) { echo 'This is a JPEG'; }
if ($image_type_check == IMAGETYPE_PNG) { echo 'This is a png'; }
To confirm what type of image. Sometimes JPG can actually be a GIF with the wrong extension