Thu, September 23, 2021
 
https://devcodepro.comdevcodepro
X
Home · Latest · Trends
18

How to check if uploaded file is image in php

How to detect if uploaded file is image or not with php
<?php
//upload.php
if(isset($_POST['query'])) {
 $image_info = @getimagesize($_FILES['image']['tmp_name']);
 if($image_info == false) {
  die('Please upload valid image file.');
 } else {
  echo 'Image file is valid';
 }
} else {
?>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" name="query" value="Upload" />
</form>
<?php } ?>
rated 20 times (19) (1)
comments: 2 / hits: 9437  / 5 years ago, mon, nov 21, 16, 10:48:23
More From » PHP
 

Comments

3
Caution
This function expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values.

Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.


https://www.php.net/manual/en/function.getimagesize.php
[#28] Friday, February 14, 2020, 4:04:08
 
Wolterhon
commented 2 years ago
3
@Wolterhon true it should be something like this:

Code:
<?php
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimetype = finfo_file($finfo, $_FILES['newimage']['tmp_name']);
if ($mimetype == 'image/jpg' || $mimetype == 'image/jpeg' || $mimetype == 'image/gif' || $mimetype == 'image/png') {
echo 'File type ' . $mimetype . ' is allowed';
} else {
echo 'The source file type ' . $mimetype . ' is not supported';
die();
}
?>
[#29] Sunday, February 16, 2020, 5:46:27
 
suppe
commented 2 years ago
Only authorized users can post. Please sign in first, or register a free account
 
Share
Posted
Ronald
Member since Sep 6, 2016
Total Code Snippets: 25
Total Comments: 2
Location: New Britain, Connecticut
Ronald snippets
5 years ago, tue, sep 6, 16, 10:11:38
comments: 0 / hits: 2571
PHP
5 years ago, tue, sep 6, 16, 10:18:23
comments: 0 / hits: 2425
PHP
5 years ago, tue, sep 6, 16, 10:42:24
comments: 0 / hits: 2791
PHP
5 years ago, fri, sep 16, 16, 1:10:12
comments: 0 / hits: 3230
PHP
5 years ago, fri, sep 16, 16, 1:12:32
comments: 0 / hits: 2144
CSS
5 years ago, fri, sep 16, 16, 1:27:33
comments: 0 / hits: 3232
PHP
5 years ago, sun, sep 25, 16, 2:52:42
comments: 1 / hits: 2560
5 years ago, thu, nov 10, 16, 4:21:59
comments: 1 / hits: 2707
PHP
5 years ago, sun, dec 25, 16, 2:44:24
comments: 0 / hits: 5214