Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago