Development

Checking if image URL is valid in PHP

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

Share
Tags: PHPWeb Dev

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago