[php] Check file extension in upload form in PHP

I check the file extension for upload or not uploaded. My example methods worked, but now I need to understand if my methods (using pathinfo) is true. Is there another better and faster way?

$filename = $_FILES['video_file']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
if ($ext !== 'gif' || $ext !== 'png' || $ext !== 'jpg') {
    echo 'error';
}

This question is related to php file-upload

The answer is


file type can be checked in other ways also. I believe this is the easiest way to check the uploaded file type.. if u are dealing with an image file then go for the following code. if you are dealing with a video file then replace the image check with a video check in the if block.. have fun

     $img_up = $_FILES['video_file']['type'];
$img_up_type = explode("/", $img_up);
$img_up_type_firstpart = $img_up_type[0];

if($img_up_type_firstpart == "image") { // image is the image file type, you can deal with video if you need to check video file type

/* do your logical code */ }


i think this might work for you

//<?php
    //checks file extension for images only
    $allowed =  array('gif','png' ,'jpg');
    $file = $_FILES['file']['name'];
    $ext = pathinfo($file, PATHINFO_EXTENSION);
        if(!in_array($ext,$allowed) ) 
            { 
//?>
<script>
       alert('file extension not allowed');
       window.location.href='some_link.php?file_type_not_allowed_error';
</script>

//<?php
exit(0);
    }
//?>

To properly achieve this, you'd be better off by checking the mime type.

function get_mime($file) {
  if (function_exists("finfo_file")) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // return mime type ala mimetype extension
    $mime = finfo_file($finfo, $file);
    finfo_close($finfo);
    return $mime;
  } else if (function_exists("mime_content_type")) {
    return mime_content_type($file);
  } else if (!stristr(ini_get("disable_functions"), "shell_exec")) {
    // http://stackoverflow.com/a/134930/1593459
    $file = escapeshellarg($file);
    $mime = shell_exec("file -bi " . $file);
    return $mime;
  } else {
    return false;
  }
}
//pass the file name as
echo(get_mime($_FILES['file_name']['tmp_name']));

Personally,I prefer to use preg_match() function:

if(preg_match("/\.(gif|png|jpg)$/", $filename))

or in_array()

$exts = array('gif', 'png', 'jpg'); 
if(in_array(end(explode('.', $filename)), $exts)

With in_array() can be useful if you have a lot of extensions to validate and perfomance question. Another way to validade file images: you can use @imagecreatefrom*(), if the function fails, this mean the image is not valid.

For example:

function testimage($path)
{
   if(!preg_match("/\.(png|jpg|gif)$/",$path,$ext)) return 0;
   $ret = null;
   switch($ext)
   {
       case 'png': $ret = @imagecreatefrompng($path); break;
       case 'jpeg': $ret = @imagecreatefromjpeg($path); break;
       // ...
       default: $ret = 0;
   }

   return $ret;
}

then:

$valid = testimage('foo.png');

Assuming that foo.png is a PHP-script file with .png extension, the above function fails. It can avoid attacks like shell update and LFI.


use this function

 function check_image_extension($image){

        $images_extentions = array("jpg","JPG","jpeg","JPEG","png","PNG");

        $image_parts = explode(".",$image);

        $image_end_part = end($image_parts);

        if(in_array($image_end_part,$images_extentions ) == true){

            return time() . "." . $image_end_part;


        }else{

            return false;
        }


    }

Checking the file extension is not considered best practice. The preferred method of accomplishing this task is by checking the files MIME type.

From PHP:

<?php
    $finfo = finfo_open(FILEINFO_MIME_TYPE); // Return MIME type
    foreach (glob("*") as $filename) {
        echo finfo_file($finfo, $filename) . "\n";
    }
    finfo_close($finfo);
?>

The above example will output something similar to which you should be checking.

text/html
image/gif
application/vnd.ms-excel

Although MIME types can also be tricked (edit the first few bytes of a file and modify the magic numbers), it's harder than editing a filename. So you can never be 100% sure what that file type actually is, and care should be taken about handling files uploaded/emailed by your users.


pathinfo is cool but your code can be improved:

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

Of course simply checking the extension of the filename would not guarantee the file type as a valid image. You may consider using a function like getimagesize to validate uploaded image files.


How to validate file extension (jpg/jpeg only) on a form before upload takes place. A variation on another posted answer here with an included data filter which may be useful when evaluating other posted form values. Note: error is left blank if empty as this was an option for my users, not a requirement.

<?php
if(isset($_POST['save'])) {

//Validate image
if (empty($_POST["image"])) {
$imageError = "";
} else {
$image = test_input($_POST["image"]);
$allowed =  array('jpeg','jpg');
$ext = pathinfo($image, PATHINFO_EXTENSION);
if(!in_array($ext,$allowed) ) {
$imageError = "jpeg only";
}
}

}

// Validate data
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
<?

Your html will look something like this;

<html>
<head>
</head>

<body>
<!-- Validate -->
<?php include_once ('validate.php'); ?>

<!-- Form -->
<form method="post" action="">

<!-- Image -->
<p>Image <?php echo $imageError; ?></p>
<input type="file" name="image" value="<?php echo $image; ?>" />

<p><input type="submit" name="save" value="SAVE" /></p>
</form>

</body>
</html>

Not sure if this would have a faster computational time, but another option...

$acceptedFormats = array('gif', 'png', 'jpg');

if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
    echo 'error';
}