How does check_ajax_referer() really work?

大兔子大兔子 提交于 2019-12-03 08:57:21
brasofilo

Revising some AJAX procedures, I came to the same question. And it's a simple matter of checking the function code:

function check_ajax_referer( $action = -1, $query_arg = false, $die = true ) {
    if ( $query_arg )
        $nonce = $_REQUEST[$query_arg];
    else
        $nonce = isset($_REQUEST['_ajax_nonce']) ? $_REQUEST['_ajax_nonce'] : $_REQUEST['_wpnonce'];

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

    if ( $die && false == $result ) {
        if ( defined( 'DOING_AJAX' ) && DOING_AJAX )
            wp_die( -1 );
        else
            die( '-1' );
    }

    do_action('check_ajax_referer', $action, $result);

    return $result;
}

If wp_verify_nonce is false and you haven't sent false in the $die parameter, then it will execute wp_die( -1 );.


In your sample code, check_ajax_referer() will break the execution and return -1 to the AJAX call. If you want to handle the error yourself, add the parameter $die and do your stuff with $do_check:

$do_check = check_ajax_referer( 'myplg-nonce', 'nonce', false ); 

Note that the proper way to handle AJAX in WordPress is: register, enqueue and localize the JavaScript files using wp_enqueue_scripts instead of wp_print_scripts.
See Use wp_enqueue_scripts() not wp_print_styles().

It is just a test that the "nonce" code matches what was given, so a hacker can't cut in and get a shortcut to your database. If the security code doesn't match, the php will die and the page will halt.

"If you code is correctly verified it will continue past, if not it will trigger die('-1'); stopping your code dead."

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!