Home >Backend Development >PHP Tutorial >Is the uploaded file really an image? How to verify image files in PHP.
Verifying Image Files in PHP
When receiving files in PHP, it's crucial to ensure they are authentic images for security reasons. Relying solely on file extension checks can be unreliable, as malicious users can rename scripts with image-like extensions.
Using getimagesize()
The getimagesize() function offers a comprehensive approach for determining whether a received file is an image. It returns an array containing information about the image, including its width, height, and MIME type. Here's how to implement it:
<code class="php">if (@is_array(getimagesize($mediapath))) { $image = true; } else { $image = false; }</code>
If the getimagesize() function successfully retrieves an array of information, it indicates that the file is a genuine image. Otherwise, it is likely a non-image file.
Sample Output
Here's an example of the output from getimagesize():
Array ( [0] => 800 [1] => 450 [2] => 2 [3] => width="800" height="450" [bits] => 8 [channels] => 3 [mime] => image/jpeg)
This output shows that the file is indeed an image with a width of 800 pixels, a height of 450 pixels, and a MIME type of image/jpeg.
The above is the detailed content of Is the uploaded file really an image? How to verify image files in PHP.. For more information, please follow other related articles on the PHP Chinese website!