WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/check ajax referer

Description

This function can be overridden by plugins. If no plugin redefines this function, then the standard functionality will be used.

The standard function verifies the AJAX request, to prevent any processing of requests which are passed in by third-party sites or systems.

Nonces should never be relied on for authentication, authorization or access control. Protect your functions using current_user_can() and always assume that nonces can be compromised.

Usage

<?php check_ajax_referer$action$query_arg$die ?>

Parameters

$action
(string) (optional) Action nonce
Default: -1
$query_arg
(string) (optional) where to look for nonce in $_REQUEST (since 2.5)
Default: false
$die
(boolean) (optional) whether to die if the nonce is invalid
Default: true

Return Values

(boolean) 
If parameter $die is set to false, this function will return a boolean of true if the check passes or false if the check fails.

Examples

In your main file, set the nonce like this:

<?php
//Set Your Nonce
$ajax_nonce = wp_create_nonce( "my-special-string" );
?>

<script type="text/javascript">
jQuery(document).ready(function($){
	var data = {
		action: 'my_action',
		security: '<?php echo $ajax_nonce; ?>',
		my_string: 'Hello World!'
	};
	$.post(ajaxurl, data, function(response) {
		alert("Response: " + response);
	});
});
</script>

In your ajax file, check the referrer like this. (As the $die parameter isn't set to false in this example, processing will stop immediately if the test fails.)

add_action( 'wp_ajax_my_action', 'my_action_function' );
function my_action_function() {
	check_ajax_referer( 'my-special-string', 'security' );
	echo sanitize_text_field( $_POST['my_string'] );
	wp_die();
}

Notes

  • This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.
  • If $query_arg is not specified (i.e. defaults to false), then the function will look for the nonce in '_ajax_nonce'. If that is not set, then it will assume that the nonce is in '_wpnonce', regardless of whether that query arg actually exists.
  • If $die is set to true, execution of the script will be stopped if the nonce cannot be verified, and the output will be '-1'.

Change Log

Source File

check_ajax_referer() is located in wp-includes/pluggable.php.

Related

Nonce functions: wp_nonce_ays(), wp_nonce_field(), wp_nonce_url(), wp_verify_nonce(), wp_create_nonce(), check_admin_referer(), check_ajax_referer(), wp_referer_field()

See also

External Resources

See also index of Function Reference and index of Template Tags.