简体   繁体   中英

How to check the file type of the file upload in HTML form?

Here is the file upload code. It works in such a way that it accepts all the image extensions. But it needs to validate the file type (video, word doc etc). I need it to only upload images. For an example what happens now is that when I select a word document and submit my form, it shows a bunch of errors, inserts the record but not the file. What should happen is that, if the file is anything other than an image, it should not let the user insert the record. Should get an error message saying to check the file type when the form is submitted. Please assist me in achieving this.

if( isset($_FILES['img']) )
    {
        //resizing the image
        $image = new SimpleImage();
        $image->load($_FILES['img']['tmp_name']);
        $image->resizeToHeight(180);
        $info =  pathinfo($_FILES['img']['name']);

        $file = 'uploads/' . basename($_FILES['img']['name'],'.'.$info['extension']) . '.png';  

        if ($image->save($file))
        { 
            if($fp = fopen($file , 'rb'))
            {
                $data = fread($fp, filesize($file));
                //encoding the the image only to text so can be stored in DB
                $data = base64_encode($data);
                fclose($fp);
            }
        }
        else
        {
            $error = '<p id="failed">Invalid Image</p>';
        }

In older PHP versions you can use mime_content_type . However if you have PHP > 5.3 you should use the finfo_* functions

You should also check is_uploaded_file() rather than isset()

if( is_uploaded_file( $_FILES['img']['tmp_name'] ) ) {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $type = finfo_file( $_FILES['img']['tmp_name'] );
    if( $type == 'image/gif' ) { // for example
        // do stuff
    }
}

You need to check MIME type on the image, something like that:

if (isset($_FILES['img'])) {
    $file = $_FILES['img'];

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime  = finfo_file($finfo, $file['tmp_name']);
    finfo_close($finfo);

    if (strpos($mime, 'image') === false) {
        die('The submitted file is not an image!');
    }

    // Uploading code..
}

If mime string has 'image' in it, then it's image. Hope that will help.

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