WordPress at a glance

wp_referer_field() WP 2.0.4

Display or retrieve a hidden input field for form with the current page URI value (referer).

The referer link is the current Request URI — $_SERVER['REQUEST_URI']. The input name is _wp_http_referer, in case you wanted to check manually:

<input type="hidden" name="_wp_http_referer" value="/current-page" />

No Hooks.

Return

String. Referer field HTML markup.

Usage

wp_referer_field( $echo );
$echo(true/false)
Whether to echo or return the referer field.
Default: true

Examples

#1 Redirect back

// has operation
if ( $doaction ) {
	// do something
}
// no operation, redirect user back
elseif ( ! empty($_REQUEST['_wp_http_referer']) ) {
	 wp_save_redirect( $_REQUEST['_wp_http_referer'] );
	 exit;
}

#2 Let's add the hidden _wp_http_referer field and check it.

Let's add a hidden _wp_http_referer field to our form and then check this field to make sure that the request came from the page we need. Suppose that the page with the form has /my-page URL.

Code of the form:

<form action="/check.php" method="post">
	... other fields ...
	<?php wp_referer_field() ?>
	... submit button ...
</form>

wp_referer_field() will print:

<input type="hidden" name="_wp_http_referer" value="/my-page" />

Code of the check.php:

if( $_POST['_wp_http_referer'] === '/my-page' ){
	// Check passed! Handle data here.
}
else {
	// Check failed!
}

Code of wp referer field: wp-includes/functions.php VER 5.1.1

<?php
function wp_referer_field( $echo = true ) {
	$referer_field = '<input type="hidden" name="_wp_http_referer" value="' . esc_attr( wp_unslash( $_SERVER['REQUEST_URI'] ) ) . '" />';

	if ( $echo ) {
		echo $referer_field;
	}
	return $referer_field;
}

Related Functions

From tag: form functions

More from tag: nonce (security protection defence)

More from category: Security

No comments
    Hello, !     Log In . Register