To check if an image is valid in PHP, you can use the getimagesize()
function. This function returns an array containing the dimensions and MIME type of the image file. If getimagesize()
returns false
, the file is not a valid image.
You can use the returned MIME type to further validate the image. For example, you might only want to accept JPEG or PNG files. You can also use the exif_read_data()
function to read the EXIF data from the image and perform additional validations.
Here is an example code snippet that demonstrates how to check if an image file is valid:
main.php751 chars33 lines
This code snippet checks if the file exists, then uses getimagesize()
to get the image size information. If getimagesize()
returns false
, the file is not a valid image. If the MIME type is not IMAGETYPE_JPEG
or IMAGETYPE_PNG
, the file is also not valid. Finally, the code uses exif_read_data()
to read the EXIF data from the image, which can be used to perform additional validations.
gistlibby LogSnag