How to check uploaded file type in PHP-ThrowExceptions

Exception or error:

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?

How to solve:

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.

Answer:

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);

Answer:

Sure you could check if it’s an image with exif, but a better way I think is to do with finfo like this:

$allowed_types = array ( 'application/pdf', 'image/jpeg', 'image/png' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['datei']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
    die ( 'Please upload a pdf or an image ' );
}
finfo_close( $fileInfo );

Answer:

The best way in my opinion is first to use getimagesize() followed by imagecreatefromstring().

    $size = getimagesize($filename);
    if ($size === false) {
        throw new Exception("{$filename}: Invalid image.");
    }
    if ($size[0] > 2500 || $size[1] > 2500) {
        throw new Exception("{$filename}: Image too large.");
    }

    if (!$img = @imagecreatefromstring(file_get_contents($filename))) {
        throw new Exception("{$filename}: Invalid image content.");
    }

Checking by getimagesize() prevents some DoS attacks, because we don’t have to try to imagecreatefromstring() from every file provided by the user, either non-image file or file too big. Unfortunately, according to PHP docs cannot be relied on for checking image type content.

The imagecreatefromstring() finally tries to open the file as an image – if is succeeds – we have an image.

Answer:

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!

Answer:

In PHP 5.5 I use this function for getting file type and check if image:

function getFileType( $file ) {
    return image_type_to_mime_type( exif_imagetype( $file ) );
}

// Get file type
$file_type = getFileType( 'path/to/images/test.png' );
echo $file_type;
// Prints image/png
// 1. All images have mime type starting with "image"
// 2. No other non-image mime types contain string "image" in it 

Then you could do:

if ( strpos( $filetype, 'image' ) !== false ) {
    // This is an image 
}

Complete list of mime types: http://www.sitepoint.com/web-foundations/mime-types-complete-list/

Answer:

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.

Answer:

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 !!';
}

Answer:

WARNING: the following answer does not actually check the file type. It only checks the name. It is not suitable for actual security purposes.

EDIT: Don’t Use this method as it serves no security check. I am leaving this answer here so that no one makes the same mistake like me by trying this.


I tried the following and it worked for me:

$allowed =  array('gif','png' ,'jpg', 'pdf');
$filename = $_FILES['input_tag_name']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
    echo 'error';
}

Source link

Leave a Reply

Your email address will not be published. Required fields are marked *