WordPress.org

Ready to get started?Download WordPress

Codex

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

Function Reference/check ajax referer

Contents

Description

This function can be replaced via plugins. If plugins do not redefine these functions, then this will be used instead.

Verifies the AJAX request to prevent processing requests external of the blog.

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 $die is set to false this function will return true / false

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:

add_action( 'wp_ajax_my_action', 'my_action_function' );
function my_action_function() {
	check_ajax_referer( 'my-special-string', 'security' );
	echo $_POST['my_string'];
	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_explain_nonce(), 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.