函数文档

sanitize_url()

💡 云策文档标注

概述

sanitize_url() 函数用于清理 URL,适用于数据库存储或重定向场景。它本质上是调用 esc_url() 函数并指定 'db' 上下文,确保 URL 的安全性和有效性。

关键要点

  • 函数接受两个参数:必需参数 $url(要清理的 URL)和可选参数 $protocols(可接受的协议数组,默认为 wp_allowed_protocols() 的返回值)。
  • 返回值为经过 esc_url() 处理后的清理 URL,使用 'db' 上下文。
  • 该函数在 WordPress 6.9.0 版本中新增了自动添加 https:// 前缀的功能(如果 URL 无协议且 $protocols 的第一个元素是 'https')。
  • 历史版本中,该函数曾被弃用(2.8.0 版本)并恢复(5.9.0 版本),开发者需注意兼容性。

代码示例

$new_input = sanitize_url( $input, array( 'http', 'https' ) );

📄 原文内容

Sanitizes a URL for database or redirect usage.

Description

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

Return

string The cleaned URL after esc_url() is run with the 'db' context.

Source

function sanitize_url( $url, $protocols = null ) {
	return esc_url( $url, $protocols, 'db' );
}

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'.
5.9.0 Restored (un-deprecated).
2.8.0 Deprecated in favor of esc_url_raw() .
2.3.1 Introduced.

User Contributed Notes