sanitize_file_name( string $filename ): string
- Since
- 2.1.0
- Source
wp-includes/formatting.php:2018
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.10
- 6.8.11
- 6.9.10
- 7.0.7
- 7.1.3
Present in every tracked release (6.7.10 to 7.1.3), 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
- 51–106
- 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 130.
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 |
|---|---|---|
seems_utf8() && $filename | 51–58 | remove_accents(), seems_utf8(), apply_filters(), explode(), apply_filters() |
seems_utf8() && !$filename | 63–73 | remove_accents(), seems_utf8(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), apply_filters() |
seems_utf8() && $filename | 67–75 | remove_accents(), seems_utf8(), apply_filters(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
!seems_utf8() && $filename | 67–74 | remove_accents(), seems_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), apply_filters(), explode(), apply_filters() |
seems_utf8() && !$filename | 79–90 | remove_accents(), seems_utf8(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
!seems_utf8() && !$filename | 79–89 | remove_accents(), seems_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), apply_filters(), wp_get_mime_types(), wp_check_filetype(), explode(), apply_filters() |
!seems_utf8() && $filename | 83–91 | remove_accents(), seems_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), apply_filters(), explode(), array_shift(), array_pop(), get_allowed_mime_types(), apply_filters() |
!seems_utf8() && !$filename | 95–106 | remove_accents(), seems_utf8(), pathinfo(), pathinfo(), sanitize_title_with_dashes(), 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 | 130 | 51–106 | 13 | |
| 8.5 | 130 | 51–106 | 13 | |
| 8.4 | 130 | 51–106 | 13 | 30 fewer instructions than PHP 8.3 |
| 8.3 | 160 | 69–130 | 13 | |
| 8.2 | 160 | 69–130 | 13 | |
| 8.1 | 160 | 69–130 | 13 | |
| 7.4 | 160 | 69–130 | 13 |
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 2049 (+31 into the body)
Filters the list of characters to remove from a filename.
- apply_filters( sanitize_file_name )filterline 2071 (+53 into the body)
Filters a sanitized filename string.
- apply_filters( sanitize_file_name )filterline 2111 (+93 into the body)
Filters a sanitized filename string.
Uses · 8
- remove_accents()Converts all accent characters to ASCII characters.
- seems_utf8()Checks to see if a string is utf8 encoded.
- sanitize_title_with_dashes()Sanitizes a title, replacing whitespace and a few other characters with dashes.
- 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 ) ); // Check for support for utf8 in the installed PCRE library once and store the result in a static. static $utf8_pcre = null; if ( ! isset( $utf8_pcre ) ) { // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged $utf8_pcre = @preg_match( '/^./u', 'a' ); } if ( ! seems_utf8( $filename ) ) { $_ext = pathinfo( $filename, PATHINFO_EXTENSION ); $_name = pathinfo( $filename, PATHINFO_FILENAME ); $filename = sanitize_title_with_dashes( $_name ) . '.' . $_ext; } if ( $utf8_pcre ) { $filename = preg_replace( "#\x{00a0}#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; } } if ( ! $allowed ) { $filename .= '_'; }Changelog
Introduced in 2.1.0. Unchanged from 6.7.10 through 7.1.3.
Signature, return type and hooks compared across 5 parsed releases.
About this page
- Parsed data
- Generated from the wordpress-develop 6.7.10 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.