简体   繁体   English

Wordpress:按MIME类型限制文件上传

[英]Wordpress: Restrict file uploads by MIME type

I've built a simple file uploaded-er within a WP plugin. 我在WP插件中构建了一个简单的upload-er文件。 In the plugins function.php file I've added the following filter which adds .xml file types in to WP's list of allowed MIME types: 在插件function.php文件中,我添加了以下过滤器,该过滤器将.xml文件类型添加到WP允许的MIME类型列表中:

add_filter('upload_mimes','add_custom_mime_types');
function add_custom_mime_types($mimes){
    return array_merge($mimes,array (
        'xml' => 'application/xml'
    ));
}

My question is, how do I check the MIME type of an upload file, denying upload to the server if the MIME type does not match those MIME types which exist in the master MIME type array. 我的问题是,如何检查上载文件的MIME类型,如果MIME类型与主MIME类型数组中存在的那些MIME类型不匹配,则拒绝上载到服务器。 For completeness here is the code which handles the file uploads: 为了完整起见,下面是处理文件上传的代码:

if((isset($_POST["submit"])) && (!empty($_FILES['uploadedfile']))){

    if($fileType !== "xml"){
        $errorType = "Incorrect file type";
        }
    if(file_exists($fullPath)){
        $errorType = "File already exist";
        }
    if($_FILES['uploadedfile']['size'] > 100000){
        $errorType = "File is too large";
        }
    if(!empty($errorType))
        {
    echo "Error $errorType";
        }
    else{
        if(rename($_FILES['uploadedfile']['tmp_name'], $fullPath)){
            echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";
            }
        } 
    }

I need to add an if statement which checks the MIME type of the upload against WP's allowed MIME types. 我需要添加一条if语句,以根据WP允许的MIME类型检查上载的MIME类型。 I'm unsure how to do this though. 我不确定如何执行此操作。 Regards. 问候。

You use get_allowed_mime_types to get allowed MIME types in Wordpress: 您可以使用get_allowed_mime_types来获取Wordpress中允许的MIME类型:

$allowed = get_allowed_mime_types($user); user is optional 用户是可选的

You use mime_content_type to get the file's MIME type in PHP: 您可以使用mime_content_type在PHP中获取文件的MIME类型:

$mime = mime_content_type($fullPath);

Check for truth if MIME is allowed: 如果允许MIME,请检查真相:

$exists = in_array($mime, $allowed);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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