wp_redirect と wp_safe_redirect

wp_redirect() と wp_safe_redirect() があるんですね。比べてみました。

wp_redirect()

まず、wp_redirect() は wp-includes/pluggable.php にあるんですね。オレオレwp_redirect()を定義できるということですね。wp_redirect()は色々なところから呼び出されているので、書き換えられるのは便利なような、書き換えて起こってしまうことが怖いような。。。別途、my_redirect()を定義したほうがよい気もします。

WordPressのいろんなところから呼び出されるwp_redirect()の図

WordPressのいろんなところから呼び出されるwp_redirect()の図


IISサーバのケアがありつつ、リダイレクト先とリダイレクトのステータスを引数として指定でき、かつフィルターで書き換えることもできるようになってます。(なんでpluggableにあるんだろ。。。)

wp_sanitize_redirect() も同じ pluggable.php で定義されてます。余計な文字を取り除いたりしてサニタイズしています。

if ( !function_exists('wp_redirect') ) :
/**
 * Redirects to another page.
 *
 * @since 1.5.1
 * @uses apply_filters() Calls 'wp_redirect' hook on $location and $status.
 *
 * @param string $location The path to redirect to
 * @param int $status Status code to use
 * @return bool False if $location is not set
 */
function wp_redirect($location, $status = 302) {
	global $is_IIS;

	$location = apply_filters('wp_redirect', $location, $status);
	$status = apply_filters('wp_redirect_status', $status, $location);

	if ( !$location ) // allows the wp_redirect filter to cancel a redirect
		return false;

	$location = wp_sanitize_redirect($location);

	if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
		status_header($status); // This causes problems on IIS and some FastCGI setups

	header("Location: $location", true, $status);
}
endif;

wp_safe_redirect()

wp_safe_redirect()は、リダイレクト先が許可されたホストなのかどうかを確認してからリダイレクトしています。なので、外から受け取ったURLにリダイレクトするときなんかに便利です。

同じ、pluggable.phpにあるwp_validate_redirect($location, admin_url())がホストをチェックしてます。

if ( !function_exists('wp_safe_redirect') ) :
/**
 * Performs a safe (local) redirect, using wp_redirect().
 *
 * Checks whether the $location is using an allowed host, if it has an absolute
 * path. A plugin can therefore set or remove allowed host(s) to or from the
 * list.
 *
 * If the host is not allowed, then the redirect is to wp-admin on the siteurl
 * instead. This prevents malicious redirects which redirect to another host,
 * but only used in a few places.
 *
 * @since 2.3
 * @uses wp_validate_redirect() To validate the redirect is to an allowed host.
 *
 * @return void Does not return anything
 **/
function wp_safe_redirect($location, $status = 302) {

	// Need to look at the URL the way it will end up in wp_redirect()
	$location = wp_sanitize_redirect($location);

	$location = wp_validate_redirect($location, admin_url());

	wp_redirect($location, $status);
}
endif;

この記事が気に入ったら
フォローしてね!

よかったらシェアしてね!

著者について

コメント

コメントする

目次
閉じる