How to Determine If a File is an Image in PHP
Verifying the authenticity of an uploaded file as an image is crucial for security purposes. While checking the file extension may seem inadequate, PHP provides reliable methods for image verification.
getimagesize() Function
The getimagesize() function stands out as the most definitive solution for this task. It analyzes the file's contents and returns an array containing information about the image, including width, height, mime type, and other attributes:
if (@is_array(getimagesize($mediapath))) {
$image = true;
} else {
$image = false;
}
Here's a sample output from getimagesize():
Array (
[0] => 800
[1] => 450
[2] => 2
[3] => width="800" height="450"
[bits] => 8
[channels] => 3
[mime] => image/jpeg)
This array structure confirms that the file is an image, making getimagesize() a highly accurate method for image verification.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3