wp_sanitize_redirect()
云策文档标注
概述
wp_sanitize_redirect() 函数用于清理 URL,确保其在重定向中安全使用。它通过编码空格、移除无效字符和控制字符,以及处理 UTF-8 序列来净化 URL。
关键要点
- 参数 $location 是必需的字符串,表示要重定向的路径。
- 返回值为经过清理的 URL 字符串。
- 函数内部步骤包括:将空格编码为 %20、使用正则表达式处理 UTF-8 字符、移除非法字符、调用 wp_kses_no_null() 移除空字符,以及通过 _deep_replace() 删除 %0D 和 %0A。
- 相关函数包括 wp_redirect()、wp_safe_redirect() 和 wp_validate_redirect()。
- 自 WordPress 2.3.0 版本引入。
代码示例
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 );
}
原文内容
Sanitizes a URL for use in a redirect.
Parameters
$locationstringrequired-
The path to redirect to.
Source
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 );
}
Changelog
| Version | Description |
|---|---|
| 2.3.0 | Introduced. |