wp_sanitize_redirect()WP 2.3.0

Sanitizes a URL for use in a redirect.

Pluggable function — this function can be replaced from a plugin. It means that this function is defined (works) only after all plugins are loaded (included), but before this moment this function has not defined. Therefore, you cannot call this and all functions depended on this function directly from a plugin code. They need to be called on plugins_loaded hook or later, for example on init hook.

Function replacement (override) — in must-use or regular plugin you can create a function with the same name, then it will replace this function.

1 time — 0.000309 sec (fast) | 50000 times — 0.20 sec (very fast) | PHP 7.1.5, WP 4.8.2

No Hooks.

Return

String. Redirect-sanitized URL.

Usage

wp_sanitize_redirect( $location );
$location(string) (required)
The path to redirect to.

Examples

0

#1 Example of cleaning a malicious URL

$url = 'http://test.example.com/redirect.php?page=%0d%0aContent-Type: text/html%0d%0aHTTP/1.1 200 OK%0d%0aContent-Type: text/html%0d%0aContent-
Length:%206%0d%0a%0d%0a%3Chtml%3EHACKED%3C/html%3E.';

echo wp_sanitize_redirect( $url );

//> http://test.example.com/~arpit/redirect.php?page=Content-Type:text/htmlHTTP/1.1200OKContent-Type:text/htmlContent-Length:%206%3Chtml%3EHACKED%3C/html%3E.
0

#2 Note - the function removes spaces

$url = '/inventory/certified new used/';

echo wp_sanitize_redirect( $url ); // /inventory/certifiednewused/

Changelog

Since 2.3.0 Introduced.

wp_sanitize_redirect() code WP 6.7.1

function wp_sanitize_redirect( $location ) {
	// Encode spaces.
	$location = str_replace( ' ', '%20', $location );

	$regex    = '/
	(
		(?: [\xC2-\xDF][\x80-\xBF]        # double-byte sequences   110xxxxx 10xxxxxx
		|   \xE0[\xA0-\xBF][\x80-\xBF]    # triple-byte sequences   1110xxxx 10xxxxxx * 2
		|   [\xE1-\xEC][\x80-\xBF]{2}
		|   \xED[\x80-\x9F][\x80-\xBF]
		|   [\xEE-\xEF][\x80-\xBF]{2}
		|   \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
		|   [\xF1-\xF3][\x80-\xBF]{3}
		|   \xF4[\x80-\x8F][\x80-\xBF]{2}
	){1,40}                              # ...one or more times
	)/x';
	$location = preg_replace_callback( $regex, '_wp_sanitize_utf8_in_redirect', $location );
	$location = preg_replace( '|[^a-z0-9-~+_.?#=&;,/:%!*\[\]()@]|i', '', $location );
	$location = wp_kses_no_null( $location );

	// Remove %0D and %0A from location.
	$strip = array( '%0d', '%0a', '%0D', '%0A' );
	return _deep_replace( $strip, $location );
}