esc_url_raw()
云策文档标注
概述
esc_url_raw() 函数用于对 URL 进行清理,适用于数据库查询或重定向场景。它是 sanitize_url() 的别名,不进行实体转义,区别于 esc_url()。
关键要点
- esc_url_raw() 是 sanitize_url() 的别名,用于清理 URL 以供数据库或重定向使用。
- 与 esc_url() 不同,esc_url_raw() 不替换实体,因此不适合直接显示 URL,应使用 esc_url() 进行显示。
- 该函数不能作为 HTTP 请求的唯一清理器,因为它无法防御 SSRF 等安全攻击。
- 参数包括必需的 $url 字符串和可选的 $protocols 数组(默认为 wp_allowed_protocols() 的返回值)。
- 从 WordPress 6.1.0 起变为 sanitize_url() 的别名,6.9.0 版本增加了对无协议 URL 自动添加 https:// 的支持。
代码示例
$url = 'http://wordpress.org';
$response = wp_remote_get( esc_url_raw( $url ) ); // 无需转义实体
if ( ! is_wp_error( $response ) ) {
echo wp_remote_retrieve_body( $response );
}注意事项
- 不要将 esc_url_raw() 作为 HTTP 请求的唯一清理器,因为它无法防御 SSRF 等攻击。
- esc_url_raw() 不适用于显示 URL,应使用 esc_url() 替代。
原文内容
Sanitizes a URL for database or redirect usage.
Description
This function is an alias for sanitize_url() .
See also
Parameters
$urlstringrequired-
The URL to be cleaned.
$protocolsstring[]optional-
An array of acceptable protocols.
Defaults to return value of wp_allowed_protocols() .Default:
null
Source
function esc_url_raw( $url, $protocols = null ) {
return sanitize_url( $url, $protocols );
}
Changelog
| Version | Description |
|---|---|
| 6.9.0 | Prepends https:// to the URL if it does not already contain a scheme and the first item in $protocols is 'https'. |
| 6.1.0 | Turned into an alias for sanitize_url() . |
| 2.8.0 | Introduced. |
Skip to note 2 content
Codex
Right and Wrong usage
<!-- Right --> $url = 'http://wordpress.org'; $response = wp_remote_get( esc_url_raw( $url ) ); // no need to escape entities if ( ! is_wp_error( $response ) ) { echo wp_remote_retrieve_body( $response ); }<!-- Wrong! Use esc_url instead! --> <img src="<?php echo esc_url_raw( $url ); ?>" /> <a href="<?php echo esc_url_raw( $url ); ?>">WordPress</a>