I’ve built a simple file uploaded-er within a WP plugin. 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:
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. 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. I’m unsure how to do this though. Regards.
You use
get_allowed_mime_types
to get allowed MIME types in WordPress:$allowed = get_allowed_mime_types($user);
user is optionalYou use
mime_content_type
to get the file’s MIME type in PHP:$mime = mime_content_type($fullPath);
Check for truth if MIME is allowed:
$exists = in_array($mime, $allowed);