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. if ( -1 == $action ) { 
  3. _doing_it_wrong( __FUNCTION__, __( 'You should specify a nonce action to be verified by using the first parameter.' ), '4.7' ); 
  4.  
  5. $nonce = ''; 
  6.  
  7. if ( $query_arg && isset( $_REQUEST[ $query_arg ] ) ) 
  8. $nonce = $_REQUEST[ $query_arg ]; 
  9. elseif ( isset( $_REQUEST['_ajax_nonce'] ) ) 
  10. $nonce = $_REQUEST['_ajax_nonce']; 
  11. elseif ( isset( $_REQUEST['_wpnonce'] ) ) 
  12. $nonce = $_REQUEST['_wpnonce']; 
  13.  
  14. $result = wp_verify_nonce( $nonce, $action ); 
  15.  
  16. /** 
  17. * Fires once the Ajax request has been validated or not. 
  18. * @since 2.1.0 
  19. * @param string $action The Ajax nonce action. 
  20. * @param false|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between 
  21. * 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago. 
  22. */ 
  23. do_action( 'check_ajax_referer', $action, $result ); 
  24.  
  25. if ( $die && false === $result ) { 
  26. if ( wp_doing_ajax() ) { 
  27. wp_die( -1, 403 ); 
  28. } else { 
  29. die( '-1' ); 
  30.  
  31. return $result;