Sanitizes the name of all files uploaded

Home » Snippets » Sanitizes the name of all files uploaded
0

Created with:

Visibility: 

public

Creator: Manny

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project
					<?php
add_filter( 'sanitize_file_name', 'wpturbo_sanitize_file_name', 10 );

function wpturbo_sanitize_file_name( $filename ) {
    return preg_replace( '/[^a-zA-Z0-9._-]+/', '', $filename );
}
				

This code uses the sanitize_file_name filter to modify the file name before it is stored. The filter passes the original file name as an argument, which we then sanitize with a regular expression pattern that removes all characters except for alphanumeric characters, dot, underscore and hyphen.

The add_filter function hooks our wpturbo_sanitize_file_name function into the sanitize_file_name filter with a priority of 10, which means it will be executed before any other function hooked into the same filter.

By using this code, all files uploaded to the front end and back end of your WordPress site will have their file names sanitized to a more secure format. This helps prevent malicious attacks and ensures that your files have consistent, clean names.

Register an account to save your snippets or go Pro to get more features.