Home > Backend Development > PHP Tutorial > How to Determine if an Uploaded File is an Image in PHP?

How to Determine if an Uploaded File is an Image in PHP?

DDD
Release: 2024-11-01 10:05:02
Original
592 people have browsed it

How to Determine if an Uploaded File is an Image in PHP?

Determining the Image Type of an Uploaded File in PHP

When working with file uploads, it's crucial to verify the type of file received. Assuming that a file's extension accurately reflects its type can be risky. In the case of images, you need a more reliable method of verification.

The PHP function getimagesize() provides a comprehensive solution for this problem. It inspects the file's content and returns an array with the following information:

  • Width and height of the image
  • Type of image (e.g., JPG, PNG, GIF)
  • File dimensions as a string

To use this function, simply pass the path to the uploaded file as follows:

<code class="php">if (@is_array(getimagesize($mediapath))) {
    $image = true;
} else {
    $image = false;
}</code>
Copy after login

If the getimagesize() function returns an array containing image dimensions and type, the file is identified as an image ($image is set to true). Otherwise, it's not an image ($image is set to false).

This method is reliable because it verifies the actual content of the file, not just the extension. It's the preferred approach for ensuring that received files are indeed images in PHP.

The above is the detailed content of How to Determine if an Uploaded File is an Image in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template