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:
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>
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!