函数文档

wp_kses_bad_protocol()

💡 云策文档标注

概述

wp_kses_bad_protocol() 函数用于清理字符串,移除不允许的 URL 协议。它递归处理内容,忽略空格和大小写,并能理解 HTML 实体,有效防止如 javascript:javascript:alert(57) 的嵌套攻击。

关键要点

  • 函数移除字符串开头所有非允许的 URL 协议,确保内容安全。
  • 参数包括 $content(必需,要过滤的内容)和 $allowed_protocols(必需,允许的协议数组)。
  • 返回过滤后的字符串,如果内容以 https:// 或 http:// 开头且协议在允许列表中,则快速返回。
  • 递归调用 wp_kses_bad_protocol_once() 进行深度清理,直到内容不再变化。
  • 相关函数包括 wp_kses_no_null()、esc_url() 等,用于 URL 和 HTML 属性安全处理。

代码示例

function wp_kses_bad_protocol( $content, $allowed_protocols ) {
    $content = wp_kses_no_null( $content );

    // Short-circuit if the string starts with `https://` or `http://`. Most common cases.
    if (
        ( str_starts_with( $content, 'https://' ) && in_array( 'https', $allowed_protocols, true ) ) ||
        ( str_starts_with( $content, 'http://' ) && in_array( 'http', $allowed_protocols, true ) )
    ) {
        return $content;
    }

    $iterations = 0;

    do {
        $original_content = $content;
        $content          = wp_kses_bad_protocol_once( $content, $allowed_protocols );
    } while ( $original_content !== $content && ++$iterations < 6 );
}

📄 原文内容

Sanitizes a string and removed disallowed URL protocols.

Description

This function removes all non-allowed protocols from the beginning of the string. It ignores whitespace and the case of the letters, and it does understand HTML entities. It does its work recursively, so it won’t be fooled by a string like javascript:javascript:alert(57).

Parameters

$contentstringrequired
Content to filter bad protocols from.
$allowed_protocolsstring[]required
Array of allowed URL protocols.

Return

string Filtered content.

Source

function wp_kses_bad_protocol( $content, $allowed_protocols ) {
	$content = wp_kses_no_null( $content );

	// Short-circuit if the string starts with `https://` or `http://`. Most common cases.
	if (
		( str_starts_with( $content, 'https://' ) && in_array( 'https', $allowed_protocols, true ) ) ||
		( str_starts_with( $content, 'http://' ) && in_array( 'http', $allowed_protocols, true ) )
	) {
		return $content;
	}

	$iterations = 0;

	do {
		$original_content = $content;
		$content          = wp_kses_bad_protocol_once( $content, $allowed_protocols );
	} while ( $original_content !== $content && ++$iterations < 6 );

	if ( $original_content !== $content ) {
		return '';
	}

	return $content;
}

Changelog

Version Description
1.0.0 Introduced.