Saturday, 7 November 2020

How to add a new mime type to WordPress

Setting up the webstore in WooCommerce, I tried to upload the epub files to the product pages and it presented me with an old familiar error for which there is no simple Wordpress setting:

my-e-book.epub has failed to upload due to an error. Sorry, this file type is not permitted for security reasons.

By default WordPress limits the allowed  Multipurpose Internet Mail Extension (MIME) types that can be uploaded. It's meant to prevent exploitable files containing malicious code getting on the server. E-pubs aren't in the white list. Which means you have to add additional file types yourself.

There are four common methods:

  1. Change WP multisite settings
  2. Allow Unfiltered Uploads in Your wp-config.php File
  3. Install a plugin to control the MIME tyoes white list
  4. Add a custom function to specify the additional MIME types to white list

Change multisite settings

Unfortunately this only works if you're running a Multisite Wordpress network. Scratch that.

Allow Unfiltered Uploads in Your wp-config.php File

Via FTP, edit the wp-config.php file on the server. Place the cursor above the line: 

/* That’s all, stop editing. Happy blogging. */

You can add the following code to the file:

define('ALLOW_UNFILTERED_UPLOADS', true);

Two issues with this are:

  1. this opens the floodgates to every file type on earth, which is the very security issue that Wordpress was trying to avoid by restricting allowed file types in the first place
  2. On at least half the WP installations I'm aware of, including mine, it doesn't work.

Install a plugin to control the MIME types white list

While there are several plugin's you can install for free, on my website, I've already got a thick stack of plugins that I want to thin out, not stack any higher. Beside which, this is probably overkill.

Add a custom function to specify the additional MIME types to white list

For once, a little bit of PHP code provides an easy and effective answer. Adding the following to the functions.php file add our new mime type to the existing mime type array:

function my_custom_mime_types( $mimes ) {
 
// New allowed mime types.
$mimes['epub'] = 'application/epub+zip';
 
// Optional. Remove a mime type.
unset( $mimes['exe'] );
 
return $mimes;
}
add_filter( 'upload_mimes', 'my_custom_mime_types' );


In this example, I've added the epub file extension associated with the mime type application/epub+zip. I could add more lines in the format

$mimes['mime-type'] = 'InternetMediaType/qualifier';

There's a reference list of mime types of the more common file extensions if you need it.

My example also explicitly blacklists executable files using the unset command. Just in case. RC












No comments:

Post a comment

At least try to be nice, it won't kill you...