Function Name: sanitize_file_name
WordPress provides a built-in function called sanitize_file_name() that is used to sanitize any file name. This function is especially useful when dealing with user input data that may contain special characters, which can cause issues when used in file names.
The sanitize_file_name() function works by removing any special characters or spaces from the file name and replacing them with an underscore character. It also removes any accents or non-ASCII characters to ensure compatibility with different systems.
This function is commonly used when uploading files to WordPress, such as images, audio files, or documents. It helps ensure that the file name is clean and free of any invalid characters or formatting that could cause issues with the file system or server.
Example usage code:
$filename = $_FILES['file']['name']; // get the uploaded file name $sanitized_filename = sanitize_file_name($filename); // sanitize the file name move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $sanitized_filename); // move the uploaded file to the 'uploads' folder with the sanitized filename
In this example, we are uploading a file and using the sanitize_file_name() function to sanitize the file name before moving it to the ‘uploads’ folder. This helps ensure that the filename is safe and compatible with different systems.