Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check uploaded file type in PHP

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?

like image 430
John Avatar asked Jul 19 '11 23:07

John


People also ask

How do I find my uploaded files in PHP?

The is_uploaded_file() function in PHP is an inbuilt function which is used to check whether the specified file uploaded via HTTP POST or not. The name of the file is sent as a parameter to the is_uploaded_file() function and it returns True if the file is uploaded via HTTP POST.

What is PHP file type?

A file with the . php file extension is a plain-text file that contains the source code written in the PHP (it's a recursive acronym meaning PHP: Hypertext Preprocessor) programming language. PHP is often used to develop web applications that are processed by a PHP engine on the web server.

Which of the following provides contain type of the uploaded file in PHP?

The PHP global $_FILES contains all the information of file. By the help of $_FILES global, we can get file name, file type, file size, temp file name and errors associated with file.

How check file is PDF or not in PHP?

You can check the MIME type of the file using PHP's File Info Functions. If it returns with the type 'application/pdf' then it should be a PDF.


2 Answers

Never use $_FILES..['type']. The information contained in it is not verified at all, it's a user-defined value. Test the type yourself. For images, exif_imagetype is usually a good choice:

$allowedTypes = array(IMAGETYPE_PNG, IMAGETYPE_JPEG, IMAGETYPE_GIF); $detectedType = exif_imagetype($_FILES['fupload']['tmp_name']); $error = !in_array($detectedType, $allowedTypes); 

Alternatively, the finfo functions are great, if your server supports them.

like image 158
deceze Avatar answered Sep 21 '22 21:09

deceze


In addition to @deceze, you may also finfo() to check the MIME-type of non-image-files:

$finfo = new finfo(); $fileMimeType = $finfo->file($path . $filename, FILEINFO_MIME_TYPE); 
like image 38
feeela Avatar answered Sep 20 '22 21:09

feeela