wppaste
WordPress

sanitize_file_name( string $filename ): string

Since
2.1.0
Source
wp-includes/formatting.php:2035
Sanitizes a filename, replacing whitespace with dashes.

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

Touches nothing outside its own arguments.

Scaling
Scales with input

The body loops, so the work grows with what you pass in.

Instructions
50–101

Executed per call on PHP 8.5, depending on the branch taken. The body compiles to 125.

Plugin surface
2 hooks

Third-party callbacks on 'sanitize_file_name_chars', 'sanitize_file_name' run inside this call, and their cost is not bounded by anything here.

Called by
5

5 places in core call this, so the cost is paid more often than your own code shows.

What it touches

  • hookthird-party callbacksapply_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.

WhenInstructionsCalls it makes
wp_is_valid_utf8() && $filename50–53remove_accents(), wp_is_valid_utf8(), _wp_can_use_pcre_u(), apply_filters(), explode(), apply_filters()
wp_is_valid_utf8() && !$filename62–68remove_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() && $filename66–70remove_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() && $filename66–69remove_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() && !$filename78–85remove_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() && !$filename78–84remove_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() && $filename82–86remove_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() && !$filename94–101remove_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

PHPCompiledExecutedBranchesNotes
8.6-dev12550–10112
8.512550–10112
8.412550–1011227 fewer instructions than PHP 8.3
8.315268–12212
8.215268–12212
8.115268–12212
7.415268–12212

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:

  1. apply_filters( sanitize_file_name_chars )filterline 2069 (+34 into the body)

    Filters the list of characters to remove from a filename.

  2. apply_filters( sanitize_file_name )filterline 2091 (+56 into the body)

    Filters a sanitized filename string.

  3. apply_filters( sanitize_file_name )filterline 2131 (+96 into the body)

    Filters a sanitized filename string.

Uses · 9

Used by · 5

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.

  1. 6.7.7
  2. 6.8.8
  3. 6.9.7
  4. 7.0.4
  5. 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.