Using Nonces

WordPress nonces are one-time use security tokens generated by WordPress to help protect URLs and forms from misuse.

If your theme allows users to submit data; be it in the Admin or the front-end; nonces can be used to verify a user intends to perform an action, and is instrumental in protecting against Cross-Site Request Forgery(CSRF).

An example is a WordPress site in which authorized users are allowed to upload videos. As an authorized user uploading videos is an intentional action and permitted. However, in a CSRF, a hacker can hijack (forge) the use of an authorized user and perform a fraudulent submission.

The one-time use hash generated by a nonce, prevents this type of forged attacks from being successful by validating the upload request is done by the current logged in user. Nonces are unique only to the current user’s session, so if an attempt is made to log in or out any nonces on the page become invalid.

Creating a Nonce Creating a Nonce

Top ↑

Verifying a Nonce Verifying a Nonce

  • check_admin_referer() – To verify a nonce that was passed in a URL or a form in an admin screen.
  • check_ajax_referer() – Checks the nonce (but not the referrer), and if the check fails then by default it terminates script execution.
  • wp_verify_nonce() – To verify a nonce passed in some other context.

Top ↑

Example Example

In this example, we have a basic submission form.

Create the Nonce

To secure your form with a nonce, create a hidden nonce field using wp_nonce_field() function:

<form method="post">
   <!-- some inputs here ... -->
   <?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>
</form>

Verify the Nonce

In our example we first check if the nonce field is set since we do not want to run anything if the form has not been submitted. If the form has been submitted we use the nonce field value function. If nonce verification is successful the form will process.

if ( 
    ! isset( $_POST['name_of_nonce_field'] ) 
    || ! wp_verify_nonce( $_POST['name_of_nonce_field'], 'name_of_my_action' ) 
) {

   print 'Sorry, your nonce did not verify.';
   exit;

} else {

   // process form data
}

In this example the basic nonce process:

  1. Generates a nonce with the wp_nonce_field() function.
  2. The nonce is submitted with the form submission.
  3. The nonce is verified for validity using the wp_verify_nonce() function. If not verified the request exits with an error message.