Security PHP Beginner

Limit Uploads to Safe File Types

Only allow the file types your site actually needs, such as images, PDFs and video, in the Media Library.

Tested on WordPress 7.1 PHP 8.3 No plugin needed Updated
functions.php 14 lines
add_filter( 'upload_mimes', function ( array $mimes ): array {
	// Keys must match WordPress's own list exactly.
	$allowed = [
		'jpg|jpeg|jpe',
		'png',
		'gif',
		'webp',
		'avif',
		'pdf',
		'mp4|m4v',
		'mp3|m4a|m4b',
	];
	return array_intersect_key( $mimes, array_flip( $allowed ) );
} );

Where to add this

Recommended A code snippets plugin Survives theme changes and is easy to switch off.
Child theme At the end of your child theme's functions.php file.
Must-use plugin As a .php file in wp-content/mu-plugins, starting with <?php.

Always add PHP to a staging site first, or have FTP or file manager access ready, so you can undo it if something goes wrong.

WordPress lets users upload dozens of file types, including spreadsheets, archives and audio formats most sites never use. Every extra type is more for an attacker to work with if an account is compromised. This snippet allows only the types you list.

How it works

The upload_mimes filter returns the allowed extensions and their MIME types. The snippet keeps only the entries whose keys are in $allowed. WordPress rejects anything else with “Sorry, you are not allowed to upload this file type.”

The keys must match WordPress’s own exactly, including the grouped ones like jpg|jpeg|jpe. You can see the full list with print_r( get_allowed_mime_types() );.

Things to watch

  • Add doc|docx, xla|xls|xlt|xlw or zip if your site needs them.
  • This doesn’t affect files plugins write directly to disk, such as backups.

How to test it

Try uploading a .zip file to the Media Library. It should be refused. A .jpg should still upload.

This website uses cookies to enhance your browsing experience and ensure the site functions properly. By continuing to use this site, you acknowledge and accept our use of cookies.

Accept All Accept Required Only