Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.