wp_create_nonce() and wp_verify_nonce()

use the logged in user ID and will not work for other users or if the user has logged out.

$nonce = wp_create_nonce( 'my-nonce' );
$nonce = $_REQUEST['_wpnonce'];
if (!wp_verify_nonce( $nonce, 'my-nonce' ))
    die( 'Security check' );     //Nonce is not valid.

Using with Ajax Calls

PHP handles the WordPress user_id with an ajax call for you, so the nonce functions can still work and are tied to specific users. For security you should not pass the user_id yourself, instead use the wordpress function to get it

//PHP create nonce
$AjaxNonce = wp_create_nonce( 'my-nonce-special-string' );


//Javascript use it
  var post_data = {
             'action': 'my_ajax_callback',   //The name of the ajax callback action in functions.php
             'security': '$AjaxNonce',
             'my_value_1': 9876
  };

  jQuery.post(ajaxurl, post_data);


//PHP Verify it in the ajax function
  check_ajax_referer('my-nonce-special-string', 'security');      //Check the nonce (nonces are tied to the user ID which is handled by php).  Will die(); if security cannpot be verified
  $user_id = get_current_user_id();                               //Use this if your function wants the wordpress user_id

UK Electronic Designer
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published.