"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Reliably Verify if a File is an Image in PHP?

How to Reliably Verify if a File is an Image in PHP?

Published on 2024-11-13
Browse:364

How to Reliably Verify if a File is an Image in PHP?

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.

Latest tutorial More>

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