Check if image exists in PHP?

You can use file_exists:

1
2
3
4
5
6
7
8
$filename = 'images/image.jpg';
 
if (file_exists($filename))
{
}
else
{
}

but, that won’t work if some server settings don’t allow to check for a file.

A simple alternative is to check the file size for the picture, which is allowed by any server settings (most of the time).
If the file doesn’t exists, you will get false and trigger the else statement.

Here is a good example.

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?php
error_reporting(0);
//to hide the error that will pop up if the image doesn't exist
 
$imageURL_bmp = 'images/image.bmp';
$imageURL_GIF = 'images/image.GIF';
 
	if (getimagesize($imageURL_bmp) == true) {
 
 echo'';
}
elseif (getimagesize($imageURL_GIF) == true) {
 
}
else
{}
?>

This example checks if the file is GIF or bmp. You can just put it to jpg.

ADD A COMMENT: