验证用于重定向的URL。

原型

wp_validate_redirect( string $location, string $default = '' )

描述

检查$ location是否使用允许的主机,如果它具有绝对路径。因此,插件可以在列表中设置或删除允许的主机。

参数

$location (string) (Required) 重定向以进行验证

$default (string) (Optional) 如果$ location不允许返回的值

返回值

(string)  重定向清理的URL

源文件

路径:wp-includes/pluggable.php

<?php
...
function wp_validate_redirect($location, $default = '') {
	$location = trim( $location, " tnrx08x0B" );
	// browsers will assume 'http' is your protocol, and will obey a redirect to a URL starting with '//'
	if ( substr($location, 0, 2) == '//' )
		$location = 'http:' . $location;
	// In php 5 parse_url may fail if the URL query part contains http://, bug #38143
	$test = ( $cut = strpos($location, '?') ) ? substr( $location, 0, $cut ) : $location;
	// @-operator is used to prevent possible warnings in PHP < 5.3.3.
	$lp = @parse_url($test);
	// Give up if malformed URL
	if ( false === $lp )
		return $default;
	// Allow only http and https schemes. No data:, etc.
	if ( isset($lp['scheme']) && !('http' == $lp['scheme'] || 'https' == $lp['scheme']) )
		return $default;
	// Reject if certain components are set but host is not. This catches urls like https:host.com for which parse_url does not set the host field.
	if ( ! isset( $lp['host'] ) && ( isset( $lp['scheme'] ) || isset( $lp['user'] ) || isset( $lp['pass'] ) || isset( $lp['port'] ) ) ) {
		return $default;
	}
	// Reject malformed components parse_url() can return on odd inputs.
	foreach ( array( 'user', 'pass', 'host' ) as $component ) {
		if ( isset( $lp[ $component ] ) && strpbrk( $lp[ $component ], ':/?#@' ) ) {
			return $default;
		}
	}
	$wpp = parse_url(home_url());
	/**
	 * Filters the whitelist of hosts to redirect to.
	 *
	 * @since 2.3.0
	 *
	 * @param array       $hosts An array of allowed hosts.
	 * @param bool|string $host  The parsed host; empty if not isset.
	 */
	$allowed_hosts = (array) apply_filters( 'allowed_redirect_hosts', array($wpp['host']), isset($lp['host']) ? $lp['host'] : '' );
	if ( isset($lp['host']) && ( !in_array($lp['host'], $allowed_hosts) && $lp['host'] != strtolower($wpp['host'])) )
		$location = $default;
	return $location;
}
...
?>

其他

英文文档:https://developer.wordpress.org/reference/functions/wp_validate_redirect/