简体   繁体   中英

Check file type?

I need to check a file's type on upload to make sure it's an image. What I'm thinking of doing is checking the MIME file type(from $_FILE ) and then checking that against the extension. Something like:

function checkType($file){

    $ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);
    $mime = $_FILES[$file]['type'];

    if($mime == "image/jpg" || $mime == "image/jpeg"){

        if($ext == "jpg" || $ext == "jpeg"){
            return true;
        } else{
            return false;
        }

    }

    if($mime == "image/gif"){

        if($ext == "gif"){
            return true;
        } else{
            return false;
        }

    }

    if($mime == "image/png"){

        if($ext == "png"){
            return true;
        } else{
            return false;
        }

    }

}

Is this a good approach? Suggestions?

Also, how would I go about getting the width of the image before it's finally uploaded to the server?

You should never rely on the content type provided by $_FILE as it's set by the browser, not by your server.

If you're expecting images, you should use getimagesize() to get the type of the image.

Example:

$imagedata = getimagesize($_FILES['image']['tmp_name']);
$mime = $imagedata['mime'];

You should then make sure that $mime isn't empty and that it contains a mime type that you want.

Here's an example using the Google logo: http://codepad.viper-7.com/9GBDf9

No, its bad. Mime type could not match actual file contents. To be sure what kind of uploaded file you received (or if its actually an image) you need to check file contents.

Try function like getimagesize for example. If it will return valid data then you have an image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM