How does check_ajax_referer() really work?
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."