Tue, October 27, 2020, 21:28:58
 
Home · Latest · Trends  /  PHP
17

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 19 times [  18] [ 1]  / comments: 2 / hits: 5616  / 4 years ago, mon, nov 21, 2016, 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, 04:04:08
 
Wolterhon
commented 9 months 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, 05:46:27
 
suppe
commented 9 months ago
Username
 
Your Comment
 
Share
Snippets
Using bind variables with ADODB
4 years ago, tue, sep 6, 2016
This module provides HTML and CLI interfaces for viewing key performance indicators of your database.
4 years ago, tue, sep 6, 2016
How to check if mail function is enabled on your server
4 years ago, tue, sep 6, 2016
Compare dates in smarty template file
4 years ago, fri, sep 16, 2016
Change default chrome input style CSS
4 years ago, fri, sep 16, 2016
Get domain name without Tld with PHP
4 years ago, fri, sep 16, 2016
Validating international phone numbers with jquery
4 years ago, sun, sep 25, 2016
Smarty Remove BBCode From String
4 years ago, thu, nov 10, 2016
How to check CKEditor 4 textarea not empty
4 years ago, sun, dec 25, 2016
Posted
Ronald

Ronald

Member since Sep 6, 2016
Total Code Snippets: 22
Total Comments: 1
Location: n/a
Following
User not following anyone yet.