Awwwards
TopDesignKing

Deny Upload if Filename Contains Special Characters

Every single website owner out there will find this to be incredibly helpful. At all times, only the letters a–z and numerals should be used in filenames. Special characters and/or foreign language characters are something they should never have.

I’m excluding the Hungarian alphabet characters, and in this example because they fall outside of the a-z range. If the filename contains any of the forbidden characters, doing this will prevent the user (or any user role) from uploading files (photos, documents, etc.) to WordPress media.

function weszty_web_not_allowed_characters_for_upload( $haystack, $needle, $offset = 0 ) {
    if( !is_array( $needle ) ) $needle = array( $needle );
    foreach( $needle as $query )
	if( strpos( $haystack, $query, $offset ) !== false ) return true;
    return false; 
}
	
add_filter( 'wp_handle_upload_prefilter', function( $file ) {
    $characterNotAllowed = array( 'á', 'é', 'í', 'ó', 'ö', 'ő', 'ú', 'ü', 'ű', 'Á', 'É', 'Í', 'Ó', 'Ö', 'Ő', 'Ú', 'Ü', 'Ű' );
    if ( weszty_web_not_allowed_characters_for_upload( $file['name'], $characterNotAllowed ) ) exit;
    return $file;
});

Don't be weird.

Would you like more information or do you have a question?

scroll
10%
Drag View Close play