如何检查HTML表单中文件上传的文件类型


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

这是文件上传代码。它的工作方式是接受所有图像扩展。但它需要验证文件类型(视频、Word 文档等)。我需要它只上传图像。例如,现在发生的事情是,当我选择一个word文档并提交我的表单时,它会显示一堆错误,插入记录而不是文件。应该发生的是,如果文件不是图像,则不应让用户插入记录。应该收到一条错误消息,指出在提交表单时检查文件类型。请协助我实现这一目标。

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>';
        }
您需要

检查图像上的MIME类型,如下所示:

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..
}

如果 mime 字符串中有"图像",那么它就是图像。希望这会有所帮助。

在较旧的 PHP 版本中,您可以使用 mime_content_type .但是,如果您有 PHP> 5.3,则应使用 finfo_* 函数

您还应该检查is_uploaded_file()而不是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
    }
}