Advertisements

sanitize_file_name

Definition:
function sanitize_file_name( $filename ) {}

Sanitizes a filename replacing whitespace with dashes
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. Trim period, dash and underscore from beginning and end of filename.

Parameters

  • string $filename: The filename to be sanitized

Return values

returns:The sanitized filename

Defined filters

  • sanitize_file_name_chars
    apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw)
  • sanitize_file_name
    apply_filters('sanitize_file_name', $filename, $filename_raw)
  • sanitize_file_name
    apply_filters('sanitize_file_name', $filename, $filename_raw)

Source code

function sanitize_file_name( $filename ) {

	$filename_raw = $filename;

	$special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));

	$special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);

	$filename = str_replace($special_chars, '', $filename);

	$filename = preg_replace('/[\s-]+/', '-', $filename);

	$filename = trim($filename, '.-_');



	// Split the filename into a base and extension[s]

	$parts = explode('.', $filename);



	// Return if only one extension

	if ( count($parts) <= 2 )

		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.  Munge them with a trailing underscore if they are a 2 - 5 character

	// long alpha string not in the extension whitelist.

	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 .= '_';

		}

	}

	$filename .= '.' . $extension;



	return apply_filters('sanitize_file_name', $filename, $filename_raw);

}

2771

Advertisements

No comments yet... Be the first to leave a reply!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: