WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/wp verify nonce

Description

Verify that a nonce is correct and unexpired with the respect to a specified action. The function is used to verify the nonce sent in the current request usually accessed by the $_REQUEST PHP variable.

Nonces should never be relied on for authentication or authorization, access control. Protect your functions using current_user_can(), always assume Nonces can be compromised.

Usage

<?php wp_verify_nonce$nonce$action ); ?>

Parameters

$nonce
(string) (required) Nonce to verify.
Default: None
$action
(string/int) (optional) Action name. Should give the context to what is taking place and be the same when the nonce was created.
Default: -1

Return Values

(boolean/integer) 
Boolean false if the nonce is invalid. Otherwise, returns an integer with the value of:
  • 1 – if the nonce has been generated in the past 12 hours or less.
  • 2 – if the nonce was generated between 12 and 24 hours ago.

Example

Verify an nonce created with wp_create_nonce():

<?php

// Create an nonce, and add it as a query var in a link to perform an action.
$nonce = wp_create_nonce( 'my-nonce' );

echo "<a href='myplugin.php?_wpnonce={$nonce}'>Save Something</a>";

?>

.....

<?php 

// In our file that handles the request, verify the nonce.

$nonce = $_REQUEST['_wpnonce'];

if ( ! wp_verify_nonce( $nonce, 'my-nonce' ) ) {

     die( 'Security check' ); 

} else {

     // Do stuff here.
}

?>

You may also decide to take different actions based on the age of the nonce:

<?php

$nonce = wp_verify_nonce( $nonce, 'my-nonce' );

switch ( $nonce ) {

    case 1:
        echo 'Nonce is less than 12 hours old';
    break;

    case 2:
        echo 'Nonce is between 12 and 24 hours old';
    break;

    default:
        exit( 'Nonce is invalid' );
}

?>

Change Log

Since: 2.0.3

Source File

wp_verify_nonce() is defined in wp-includes/pluggable.php

Related

Nonce functions: wp_nonce_ays(), wp_nonce_field(), wp_nonce_url(), wp_verify_nonce(), wp_create_nonce(), check_admin_referer(), check_ajax_referer(), wp_referer_field()

Nonce hooks: nonce_life, nonce_user_logged_out, explain_nonce_(verb)-(noun), check_admin_referer

External Resources

See also index of Function Reference and index of Template Tags.