harkly
harkly

Reputation: 87

How to validate image on upload?

I am playing around with some code and am wondering if both of these are needed?

I would think that if I have checked that it is an image then I would not need to verify if a correct extension is being used.

It seems redundant, but I may not be seeing the bigger picture.

// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
    && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
    $uploadOk = 0;
}

I will be resizing and possibly changing the extension, that way I don't have to store it in the database.

Upvotes: 0

Views: 1724

Answers (1)

jagad89
jagad89

Reputation: 2643

It is clearly mentioned in PHP documentation not to use getimagesize for image validation.

Caution getimagesize expects filename to be a valid image file. If a non-image file is supplied, it may be incorrectly detected as an image and the function will return successfully, but the array may contain nonsensical values. Do not use getimagesize() to check that a given file is a valid image. Use a purpose-built solution such as the Fileinfo extension instead.

So you need few more checks regarding the file mime type, for further digging into this scenario I looked into Codeignitor code. Go to this link and look into the function named _file_mime_type here they detect file mime type and later they match with allowed file mime types.

Upvotes: 1

Related Questions