Allow Only Safe File Types to Be Uploaded
Limits uploads to common images, documents, audio and video, and rejects files with a hidden second extension such as photo.php.jpg.
Opens WPIDE on
Code
// Extensions (as WordPress lists them) that may be uploaded.
$wpide_safe_upload_types = array( 'jpg|jpeg|jpe', 'png', 'gif', 'webp', 'avif', 'pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt|pps', 'pptx', 'odt', 'txt', 'csv', 'mp3|m4a|m4b', 'mp4|m4v', 'mov|qt', 'webm' );
add_filter( 'upload_mimes', function ( $mimes ) use ( $wpide_safe_upload_types ) {
return array_intersect_key( $mimes, array_flip( $wpide_safe_upload_types ) );
}, 99 );
add_filter( 'wp_handle_upload_prefilter', function ( $file ) {
$parts = explode( '.', strtolower( (string) $file['name'] ) );
array_pop( $parts ); // The real extension.
foreach ( $parts as $part ) {
if ( in_array( $part, array( 'php', 'php3', 'php4', 'php5', 'php7', 'php8', 'phtml', 'phar', 'pht', 'shtml', 'cgi', 'exe', 'htaccess' ), true ) ) {
$file['error'] = 'This file name is not allowed. Please rename the file and try again.';
break;
}
}
return $file;
} );
Notes
Remove this snippet or extend the list before uploading other file types, such as ZIP archives or fonts.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.