WordPress at a glance

check_ajax_referer() WP 1.0

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

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.

Works based on: wp_verify_nonce()

No Hooks.

Return

false/Int. False if the nonce is invalid, 1 if the nonce is valid and generated between
0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.

Usage

check_ajax_referer( $action, $query_arg, $die );
$action(int/string)
Action nonce.
Default: -1
$query_arg(false/string)
Key to check for the nonce in $_REQUEST (since 2.5). If false, $_REQUEST values will be evaluated for '_ajax_nonce', and '_wpnonce' (in that order).
Default: false
$die(true/false)
Whether to die early when the nonce cannot be verified.
Default: true

Code of check_ajax_referer: wp-includes/pluggable.php VER 5.0.1

<?php
function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
	if ( -1 == $action ) {
		_doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '4.7' );
	}

	$nonce = '';

	if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) )
		$nonce = $_REQUEST[ $query_arg ];
	elseif ( isset( $_REQUEST['_ajax_nonce'] ) )
		$nonce = $_REQUEST['_ajax_nonce'];
	elseif ( isset( $_REQUEST['_wpnonce'] ) )
		$nonce = $_REQUEST['_wpnonce'];

	$result = wp_verify_nonce( $nonce, $action );

	/**
	 * Fires once the Ajax request has been validated or not.
	 *
	 * @since 2.1.0
	 *
	 * @param string    $action The Ajax nonce action.
	 * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between
	 *                          0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
	 */
	do_action( 'check_ajax_referer', $action, $result );

	if ( $die && false === $result ) {
		if ( wp_doing_ajax() ) {
			wp_die( -1, 403 );
		} else {
			die( '-1' );
		}
	}

	return $result;
}

Related Functions

From tag: AJAX

More from tag: nonce (security protection defence)

More from category: Security

No comments
    Hello, !     Log In . Register