check_ajax_referer

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

Description

(false|int) check_ajax_referer( (int) $action = -1, (constant) $query_arg = false, (bool) $die = true ); 

Returns (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.

Parameters (3)

0. $action — Optional. (int) => -1
Action nonce.
1. $query_arg — Optional. (constant) => false
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.
2. $die — Optional. (bool) => true
Whether to die early when the nonce cannot be verified. Default true.

Usage

  1. if ( !function_exists( 'check_ajax_referer' ) ) { 
  2. require_once ABSPATH . WPINC . '/pluggable.php'; 
  3.  
  4. // Action nonce. 
  5. $action = -1; 
  6. $query_arg = false; 
  7.  
  8. // Optional. Whether to die early when the nonce cannot be verified. 
  9. // Default true. 
  10. $die = true; 
  11.  
  12. // NOTICE! Understand what this does before running. 
  13. $result = check_ajax_referer($action, $query_arg, $die); 
  14.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/pluggable.php  
  1. function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) { 
  2. $nonce = ''; 
  3.  
  4. if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) ) 
  5. $nonce = $_REQUEST[ $query_arg ]; 
  6. elseif ( isset( $_REQUEST['_ajax_nonce'] ) ) 
  7. $nonce = $_REQUEST['_ajax_nonce']; 
  8. elseif ( isset( $_REQUEST['_wpnonce'] ) ) 
  9. $nonce = $_REQUEST['_wpnonce']; 
  10.  
  11. $result = wp_verify_nonce( $nonce, $action ); 
  12.  
  13. /** 
  14. * Fires once the Ajax request has been validated or not. 
  15. * @since 2.1.0 
  16. * @param string $action The Ajax nonce action. 
  17. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between 
  18. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago. 
  19. */ 
  20. do_action( 'check_ajax_referer', $action, $result ); 
  21.  
  22. if ( $die && false === $result ) { 
  23. if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) { 
  24. wp_die( -1 ); 
  25. } else { 
  26. die( '-1' ); 
  27.  
  28. return $result;