Function and usage of check_ajax_referer() in wordpress

Question

Answers ( 1 )

    0
    2024-01-05T15:16:42+00:00

    The check_ajax_referer() function in WordPress is a security measure used to verify the authenticity of Ajax requests, ensuring they come from the site and not externally. Here's a detailed breakdown of its usage and parameters:

    Function Prototype:

    check_ajax_referer( int|string $action = -1, false|string $query_arg = false, bool $stop = true ): int|false
    

    Function Details:

    • Purpose:
      • Verifies the Ajax request to prevent processing of requests external to the blog, which is crucial for WordPress security.

    Parameters:

    1. $action (int|string, optional):

      • This is the action nonce, a unique token used to verify the source of the request.
      • Default value: -1, which indicates that no action is associated.
    2. $query_arg (false|string, optional):

      • This specifies the key to check for the nonce in the $_REQUEST global variable.
      • Since WordPress 2.5, this can be used to check a specific key for the nonce.
      • If set to false, the function will look for the nonce in $_REQUEST values under _ajax_nonce and _wpnonce keys, in that order.
      • Default value: false.
    3. $stop (bool, optional):

      • Determines whether to halt execution early when the nonce cannot be verified.
      • Default value: true, meaning the script will stop executing if the nonce is invalid.

    Return Values:

    • int:
      • Returns 1 if the nonce is valid and was generated between 0-12 hours ago.
      • Returns 2 if the nonce is valid and was generated between 12-24 hours ago.
    • false:
      • Returned if the nonce is invalid.

    Sample Usage:

    Here's an example of how check_ajax_referer() might be used in a WordPress plugin or theme:

    function my_ajax_handler() {
        // Check the nonce, and halt if it's invalid
        check_ajax_referer( 'my_action_nonce', 'nonce_field_name' );
    
        // Your AJAX request handling logic here
        // ...
    
        // Return a response
        wp_send_json_success( $response_data );
    }
    
    // Hooking the function to an action
    add_action( 'wp_ajax_my_action', 'my_ajax_handler' );
    

    In this example, check_ajax_referer() is used to verify the nonce sent with the Ajax request. The nonce is expected to be in the nonce_field_name field of the request, and it's associated with an action named my_action_nonce. If the nonce is invalid, the function halts execution due to the default $stop parameter being true. If the nonce is valid, the rest of the AJAX handling logic proceeds.

Leave an answer