sanitize_file_name( string $filename ): string
- Since
- 2.1.0
- Source
wp-includes/formatting.php:2035
Description
Removes special characters that are illegal in filenames on certain operating systems and special characters requiring special escaping to manipulate at the command line. Replaces spaces and consecutive dashes with a single dash. Trims period, dash and underscore from beginning and end of filename. It is not guaranteed that this function will return a filename that is allowed to be uploaded.
Compatibility
- WordPress
- since 2.1.0
- PHP
- 7.4–8.6-dev
- 6.7.7
- 6.8.8
- 6.9.7
- 7.0.4
- 7.1.0
Present in every tracked release (6.7.7 to 7.1.0), and compiles on PHP 7.4 through 8.6-dev.
Parameters
$filenamestring- The filename to be sanitized.
Return value
string- The sanitized filename.
Performance profile
How much work a call to sanitize_file_name() does, and what it touches: the algorithmic scaling, the Zend instruction count per call across PHP versions, the hooks it hands control to, and the core code that calls it. Measured from the compiled opcodes, not a stopwatch, so every number is identical on any machine running the same PHP version, and every function in core is ranked by cost.
- Cost class
- Light
- Scaling
- Scales with input
- Instructions
- 50–101
- Plugin surface
- 2 hooks
- Called by
- 5
Touches nothing outside its own arguments.
The body loops, so the work grows with what you pass in.
Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 125.
Third-party callbacks on 'sanitize_file_name_chars', 'sanitize_file_name' run inside this call, and their cost is not bounded by anything here.
5 places in core call this, so the cost is paid more often than your own code shows.
What it touches
- hookthird-party callbacks
apply_filters()called directly
Further down the call graph this can also reach option, cache, serialize, query and transient. Those are the worst case, several calls deep and usually down an error path, not what a normal call pays.
What one call costs · 8 distinct outcomes
One number would be a lie: the work depends on which branch runs. These are every distinct cost sanitize_file_name() can have, taken from its control-flow graph on PHP 8.5.
| When | Instructions | Calls it makes |
|---|---|---|
wp_is_valid_utf8() && $filename | 50–53 | remove_accents(), wp_is_valid_utf8(), _wp_can_use_pcre_u(), apply_filters(), explode(), apply_filters() |
wp_is_valid_utf8() && !$filename | 62–68 | remove_accents(), wp_is_valid_utf8(), _wp_can_use_pcre_u(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), apply_filters() |
wp_is_valid_utf8() && $filename | 66–70 | remove_accents(), wp_is_valid_utf8(), _wp_can_use_pcre_u(), apply_filters(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
!wp_is_valid_utf8() && $filename | 66–69 | remove_accents(), wp_is_valid_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), _wp_can_use_pcre_u(), apply_filters(), explode(), apply_filters() |
wp_is_valid_utf8() && !$filename | 78–85 | remove_accents(), wp_is_valid_utf8(), _wp_can_use_pcre_u(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
!wp_is_valid_utf8() && !$filename | 78–84 | remove_accents(), wp_is_valid_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), _wp_can_use_pcre_u(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), apply_filters() |
!wp_is_valid_utf8() && $filename | 82–86 | remove_accents(), wp_is_valid_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), _wp_can_use_pcre_u(), apply_filters(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
!wp_is_valid_utf8() && !$filename | 94–101 | remove_accents(), wp_is_valid_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), _wp_can_use_pcre_u(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
Across PHP versions
| PHP | Compiled | Executed | Branches | Notes |
|---|---|---|---|---|
| 8.6-dev | 125 | 50–101 | 12 | |
| 8.5 | 125 | 50–101 | 12 | |
| 8.4 | 125 | 50–101 | 12 | 27 fewer instructions than PHP 8.3 |
| 8.3 | 152 | 68–122 | 12 | |
| 8.2 | 152 | 68–122 | 12 | |
| 8.1 | 152 | 68–122 | 12 | |
| 7.4 | 152 | 68–122 | 12 |
An instruction is not a fixed amount of time, so a matching count is not necessarily the same speed; what it rules out is a difference in the work itself.
Hooks and filters fired · 3
3 hooks fire while sanitize_file_name() runs, in this order:
- apply_filters( sanitize_file_name_chars )filterline 2069 (+34 into the body)
Filters the list of characters to remove from a filename.
- apply_filters( sanitize_file_name )filterline 2091 (+56 into the body)
Filters a sanitized filename string.
- apply_filters( sanitize_file_name )filterline 2131 (+96 into the body)
Filters a sanitized filename string.
Uses · 9
- remove_accents()Converts all accent characters to ASCII characters.
- wp_is_valid_utf8()Determines if a given byte string represents a valid UTF-8 encoding.
- sanitize_title_with_dashes()Sanitizes a title, replacing whitespace and a few other characters with dashes.
- _wp_can_use_pcre_u()Returns whether PCRE/u (PCRE_UTF8 modifier) is available for use.
- apply_filters()Calls the callback functions that have been added to a filter hook.
- str_contains()Polyfill for `str_contains()` function added in PHP 8.0.
- wp_get_mime_types()Retrieves the list of mime types and file extensions.
- wp_check_filetype()Retrieves the file type from the file name.
- get_allowed_mime_types()Retrieves the list of allowed mime types and file extensions.
Used by · 5
- File_Upload_Upgrader::__construct()Construct the upgrader for a form.
- download_url()Downloads a URL to a local temporary file using the WordPress HTTP API.
- wp_copy_parent_attachment_properties()Copy parent attachment properties to newly cropped image.
- wp_unique_filename()Gets a filename that is sanitized and unique for the given directory.
- wp_xmlrpc_server::mw_newMediaObject()Uploads a file, following your settings.
Source code
function sanitize_file_name( $filename ) { $filename_raw = $filename; $filename = remove_accents( $filename ); $special_chars = array( '?', '[', ']', '/', '\\', '=', '<', '>', ':', ';', ',', "'", '"', '&', '$', '#', '*', '(', ')', '|', '~', '`', '!', '{', '}', '%', '+', '’', '«', '»', '”', '“', chr( 0 ) ); if ( ! wp_is_valid_utf8( $filename ) ) { $_ext = pathinfo( $filename, PATHINFO_EXTENSION ); $_name = pathinfo( $filename, PATHINFO_FILENAME ); $filename = sanitize_title_with_dashes( $_name ) . '.' . $_ext; } if ( _wp_can_use_pcre_u() ) { /** * Replace all whitespace characters with a basic space (U+0020). * * The “Zs” in the pattern selects characters in the `Space_Separator` * category, which is what Unicode considers space characters. * * @see https://www.unicode.org/reports/tr44/#General_Category_Values * @see https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-6/#G17548 * @see https://www.php.net/manual/en/regexp.reference.unicode.php */ $filename = preg_replace( '#\p{Zs}#siu', ' ', $filename ); } /** * Filters the list of characters to remove from a filename. * * @since 2.8.0 * * @param string[] $special_chars Array of characters to remove. * @param string $filename_raw The original filename to be sanitized. */ $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw ); $filename = str_replace( $special_chars, '', $filename ); $filename = str_replace( array( '%20', '+' ), '-', $filename ); $filename = preg_replace( '/\.{2,}/', '.', $filename ); $filename = preg_replace( '/[\r\n\t -]+/', '-', $filename ); $filename = trim( $filename, '.-_' ); if ( ! str_contains( $filename, '.' ) ) { $mime_types = wp_get_mime_types(); $filetype = wp_check_filetype( 'test.' . $filename, $mime_types ); if ( $filetype['ext'] === $filename ) { $filename = 'unnamed-file.' . $filetype['ext']; } } // Split the filename into a base and extension[s]. $parts = explode( '.', $filename ); // Return if only one extension. if ( count( $parts ) <= 2 ) { /** This filter is documented in wp-includes/formatting.php */ return apply_filters( 'sanitize_file_name', $filename, $filename_raw ); } // Process multiple extensions. $filename = array_shift( $parts ); $extension = array_pop( $parts ); $mimes = get_allowed_mime_types(); /* * Loop over any intermediate extensions. Postfix them with a trailing underscore * if they are a 2 - 5 character long alpha string not in the allowed extension list. */ foreach ( (array) $parts as $part ) { $filename .= '.' . $part; if ( preg_match( '/^[a-zA-Z]{2,5}\d?$/', $part ) ) { $allowed = false; foreach ( $mimes as $ext_preg => $mime_match ) { $ext_preg = '!^(' . $ext_preg . ')$!i'; if ( preg_match( $ext_preg, $part ) ) { $allowed = true; break; } }Changelog
Introduced in 2.1.0. Unchanged from 6.7.7 through 7.1.0.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 7.1.0 tag, from
src/wp-includes/formatting.php, and regenerated for each WordPress release so it tracks the code rather than a snapshot of it. - Corrections
- Something wrong on this page? Report it and it gets fixed in the next regeneration.