How to check uploaded file type in PHP

Viewed 100231

I used this code to check for the type of images,

$f_type=$_FILES['fupload']['type'];

if ($f_type== "image/gif" OR $f_type== "image/png" OR $f_type== "image/jpeg" OR $f_type== "image/JPEG" OR $f_type== "image/PNG" OR $f_type== "image/GIF")
{
    $error=False;
}
else
{
    $error=True;
}

but some users complain they get an error while uploading any type of images, while some others don't get any errors!

I was wondering if this fixes the problem:

if (mime_content_type($_FILES['fupload']['type']) == "image/gif"){...

Any comments?

9 Answers

This is a simple, one line script that I use often.

$image = "/var/www/Core/temp/image.jpg";
$isImage = explode("/", mime_content_type())[0] == "image";

Basically I am using mime_content_type() to get something like "image/jpg" and then exploding it by "/" and checking against the first element of the array to see if it says "image".

I hope it works!

That last line is close. You can use: if (mime_content_type($_FILES['fupload']['tmp_name']) == "image/gif"){...

In the case I'm currently working on, my $_FILES..['type'] reports itself as "text/csv", while both mime_content_type() and finfo() (suggested by others) report "text/plain.". As @deceze points out, $_FILES..['type'] is only useful to know what type a client thinks a file is.

you can try this

$file_extension = explode('.',$file['name']);
$file_extension = strtolower(end($file_extension));
$accepted_formate = array('jpeg','jpg','png');
if(in_array($file_extension,$accepted_formate)) {           
  echo "This is jpeg/jpg/png file";
} else {
  echo $file_extension.' This is file not allowed !!';
}
Related