1

How to check if the file uploaded file is solely an image and not video file and anything?

I tested out a simple code that will check if the uploaded file is an image.

form

<form method="post" enctype="multipart/form-data">
    <input type="file" name="photo" accept="image/*">
    <input type="submit" name="submit" value="Test">
</form>

Although I have accept="image/*", I can easily change it to All types and get a non-image file.

code to check if the file is a valid image (This is only for testing)

if($_POST['submit']) {
    $tmp_file = $_FILES['photo']['tmp_name'];
    if(mime_content_type($tmp_file)) {
        var_dump(mime_content_type($tmp_file));
    } else {
        echo 'error1';
    }
    if(getimagesize($tmp_file)) {
        var_dump(getimagesize($tmp_file));
    } else {
        echo 'error2';
    }
}

As of now I have 3 test to this, 2 passed 1 failed:

  1. Testing an image = passed.
  2. Testing a non-image valid .srt file = passed (gives an error to getimagesize)
  3. Testing a valid video file .mp4 = failed (after the submission, it is loading for 5-10 seconds and not gives any error)

What do I need to do about this? I do not know what is the problem because it does not gives any results from both var_dump() and echo 'errors'. What I do think now is that PHP is accepting the file.

Note

I need to do this so that only a valid image will be uploaded.

Note 2

The accepted answer on the marked question is not working with me.

Update

If I try to upload a video that is less than 128M it returns something. But if it is greater than 128M it gets nothing in my localhost, but I tested this in a production site it gives me a REQUEST TIME OUT.

Dumb Question
  • 365
  • 1
  • 3
  • 14

2 Answers2

1

Find file extension like this and check for valid types...

function  getextension($name){
    $count=substr_count($name,".");
    if($count>1){//some cases have two dotes
        $name= preg_replace('/\.(?=.*\.)/', '_', $name);
    }
    list($txt, $ext) = explode(".", $name);
    return $ext;
}

$name = $_FILES['imageupload']['name'];//Name of the File
$image_extension = getextension($name);

 $allowed_extension = array("jpg", "png", "gif", "bmp", "jpeg","JPG","PNG","GIF","BMP","JPEG");
 $image_extension=getextension($name);
  if (!in_array($image_extension, $allowed_extension)) {
    $error_flag = 1;
    $message = "Invalid File Format";
 }
Sanooj T
  • 1,317
  • 1
  • 14
  • 25
1

Parsing and checking extensions are not enough as per the question points to.

I suggest to check file EXIF (Exchangeable image information) data after loading a file.

You can put basic validation on basis on extension and after that if it succeed , check exif data of image.

For that you will need a separate DLL to load, that will have exif related function.

http://php.net/manual/en/ref.exif.php

developerCK
  • 4,418
  • 3
  • 16
  • 35