Verifies the Ajax request to prevent processing requests external of the blog.
Parameters
$action
int|stringoptional- Action nonce.
Default:
-1
$query_arg
false|stringoptional- 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
$stop
booloptional- Whether to stop early when the nonce cannot be verified.
Default:
true
Source
/**
* Verifies the Ajax request to prevent processing requests external of the blog.
*
* @since 2.0.3
*
* @param int|string $action Action nonce.
* @param false|string $query_arg Optional. 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.
* @param bool $stop Optional. Whether to stop early when the nonce cannot be verified.
* Default true.
* @return int|false 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.
* False if the nonce is invalid.
*/
function check_ajax_referer( $action = -1, $query_arg = false, $stop = true ) {
if ( -1 === $action ) {
_doing_it_wrong( __FUNCTION__, __( 'You should specify an action to be verified by using the first parameter.' ), '4.7.0' );
}
$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.
Changelog
Version | Description |
---|---|
2.0.3 | Introduced. |
Example
In your main file, set the nonce like this:
In your AJAX file, check the referrer like this: