WordPress at a glance

wp_safe_redirect() WP 2.3.0

Performs a safe redirect, using wp_redirect(). Before redirections check whether the host is in whitelist (in list of allowed hosts).

Before redirecting to the specified host (url), the function checks it. Redirection will occur only if the host is present in the list of allowed hosts.

If the host is not allowed, then the redirect defaults to http://site.com/wp-admin instead. This prevents malicious redirects which redirect to another host. With this approach, you can protect users from getting to an unsafe site.

The list of allowed hosts can be extended by plugins, see hook allowed_redirect_hosts().

This is a pluggable function, and it can be replaced from plugin. It means that this function is defined (works) only after all plugins are connected (included), but before this moment the function has not yet been defined... Therefore, you cannot call this and all functions depended on this function directly from a plugin code. It must be called via hook plugins_loaded or later, for example on hook init.

Function replacement (override) — in a plugin you can create a function with the same name, then it will replace this function.

No Hooks.

Return

Nothing (null).

Usage

wp_safe_redirect( $location, $status );
$location(string) (required)
The path to redirect to.
$status(int)
Status code to use.
Default: 302

Examples

#1 Secure redirection

Let's imagine that we pass a redirect link to the wp_safe_redirect() function and it changes depending on the user's actions, i.e. it can always be different. And we need to make sure that the redirection will occur only if site internal URL was passed. This code will help us:

if( isset( $_POST['location'] ) ){
	wp_safe_redirect( $_POST['location'] );
	exit;
}

Code of wp_safe_redirect: wp-includes/pluggable.php VER 5.0

<?php
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);

	/**
	 * Filters the redirect fallback URL for when the provided redirect is not safe (local).
	 *
	 * @since 4.3.0
	 *
	 * @param string $fallback_url The fallback URL to use by default.
	 * @param int    $status       The redirect status.
	 */
	$location = wp_validate_redirect( $location, apply_filters( 'wp_safe_redirect_fallback', admin_url(), $status ) );

	wp_redirect($location, $status);
}

Related Functions

From category: Uncategorized

No comments
    Hello, !     Log In . Register