allowing custom file extensions to be uploaded to wordpress

WordPress restricts types of files you can upload. it not only checks the extension of what you’re adding to the media library but also its mime type. so you cannot fool it by uploading .exe renamed to .jpeg – if you try it, you’ll get an error saying: “Sorry, this file type is not permitted for security reasons”.

to allow upload of custom file type to wordpress 5.2.2 i’ve created few lines long plugin and placed it under wp-content/plugins/allowUploadOfCustomFileType.php :

<?php
/**
 * @package allowUploadOfCustomFileType
 * @version 1.0
*/
 /*
Plugin Name: allow upload of custom file type
Plugin URI: http://kudzia.eu
Description: allow upload of .ext files
Author: pawel kudzia
Version: 1.0
Author URI: http://kudzia.eu/
*/

/*
// this is how i used to do it, it's no longer enough
function my_myme_types($mime_types){
 mime_types['ext'] = 'application/some.document';
 return $mime_types;
}
add_filter('upload_mimes', 'my_myme_types', 1, 1);*/

// and that's how i handle it now,
// based on https://wordpress.org/support/topic/cannot-import-csv-donations/
add_filter('wp_check_filetype_and_ext', function($values, $file, $filename, $mimes) {
 if ( preg_match( '/\.(ext)$/i', $filename ) ) {
  $values['ext']  = 'ext';
  $values['type'] = 'application/some.document';
 }
 return $values;
}, PHP_INT_MAX, 4);

Leave a Reply

Your email address will not be published. Required fields are marked *

(Spamcheck Enabled)