check_admin_referer('my_action') to verify a nonce. What is the typical behavior if the nonce is invalid or missing?The check_admin_referer() function verifies the nonce and if it fails, it triggers a WordPress error and stops the script execution to prevent unauthorized actions.
wp_verify_nonce and how to handle failure.wp_verify_nonce() takes the nonce value first, then the action string. It returns false if invalid, so the condition negates it to trigger wp_die().
<?php if (isset($_POST['my_nonce']) && wp_verify_nonce($_POST['my_nonce'], 'save_data')) { echo 'Nonce verified'; } else { echo 'Nonce failed'; } ?>
If the nonce is set and valid, the code echoes 'Nonce verified'. Otherwise, it echoes 'Nonce failed'.
<?php if (!wp_verify_nonce('save_data', $_POST['my_nonce'])) { wp_die('Invalid nonce'); } ?>
The first parameter to wp_verify_nonce() must be the nonce value, and the second is the action string. Reversing them causes verification to fail.
Nonces in WordPress protect against CSRF attacks by verifying that requests come from legitimate users and not attackers.
