Skip to content

Instantly share code, notes, and snippets.

@DavidWells
Forked from RalfAlbert/onetime_nonce.php
Created March 27, 2014 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DavidWells/9821083 to your computer and use it in GitHub Desktop.
Save DavidWells/9821083 to your computer and use it in GitHub Desktop.
<?php
function create_onetime_nonce( $action = -1 ) {
$time = time();
$nonce = wp_create_nonce( $time . $action );
set_transient( '_nonce_' . $time, 1, 60*60 ); // adjust the lifetime of the transient
return $nonce . '-' . $time;
}
function verify_onetime_nonce( $_nonce, $action = -1 ) {
@list( $nonce, $time ) = explode( '-', $_nonce );
// bad formatted onetime-nonce
if ( empty( $nonce ) || empty( $time ) )
return false;
$nonce_transient = get_transient( '_nonce_' . $time );
// nonce cannot be validated or has expired or was already used
if (
! wp_verify_nonce( $nonce, $time . $action ) ||
false === $nonce_transient ||
'used' === $nonce_transient
)
return false;
// mark this nonce as used
set_transient( '_nonce_' . $time, 'used', 60*60 );
// return true to mark this nonce as valid
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment