PHP Validating the File Upload [duplicate]

You should pass the tmp_name of the file* to getimagesize, it will give you the size and type of the image (if it is an image). If the passed argument is a file but not an image it returns false, that will allow you to validate.

Edit: The only reliable method of image validation is to make a copy of it using GD or Imagick – getimagesize can be easily hacked.

*: I mean, the temporal file created after upload.

For example:

if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
    $file = $_FILES['file']['tmp_name'];
    if (file_exists($file))
    {
        $imagesizedata = getimagesize($file);
        if ($imagesizedata === FALSE)
        {
            //not image
        }
        else
        {
            //image
            //use $imagesizedata to get extra info
        }
    }
    else
    {
        //not file
    }
}

This code uses file_exists just to be general. In case no file were uploaded you would get $_FILES['file']['size'] = 0, $_FILES['file']['tmp_name'] = '' and $_FILES['file']['error'] = 4. See also is_readable. For the error values see file upload errors explained at php.net.

Leave a Comment