The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Ajax Nonce

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #198970

    I’m not using WordPress, and would like a little guidance on using a nonce in Ajax form submission.

    Is there an issue in passing the nonce via ajax to PHP, and then if there is an error in the submission, generate a new nonce and pass it back to Javascript and populate the field client-side again?

    For example, I found this that seems to be what I want to do:

    But I’m not sure if there’s an issue passing the nonce to-and-fro that way.


    The reason I said no-Wordpress is because if you Google “Ajax nonce” or something similar, you get mostly WordPress answers. Answers based on WordPress-specific functions and plugs.

    I thought that a nonce is a ‘number used once’. So when a submission is NOT successfull, you’d generate a new one otherwise an attacker could continue to try to submit the form with the same token in place. No?

    I’ve never ran across a tutorial or technique that has a specific expiration of a nonce. Do you have a working example that does this? Most examples I’ve seen utilize sessions with no specific expiration.

    Thx for the reply!

    Ilan Firsov

    Basically, when you save the nonce, save the expiry along with it, and check both on submission.

    To add to this, I would verify the expiry time is not modified by an attacker.
    I’d do something like this:

    $expiry = time() + 300;
    $nonce = wp_create_nonce( 'myform' . $expiry );
    $_SESSION[$nonce] = $expiry;
    <form action=whatever method=post>
        <input type=hidden name=_wpnonce value=<?= $nonce ?>>
        <input type=submit value=Submit>
    $nonce = $_REQUEST['_wpnonce'];
    if ( isset( $_POST["_wpnonce"], $_SESSION[$_POST["_wpnonce"]] ) && wp_verify_nonce( $nonce, 'myform' . $_SESSION[$_POST["_wpnonce"]] ) && time() < $_SESSION[$_POST["_wpnonce"]] ) {
      // do stuff

    Though usually I would not add the expiry to the session and just hardcode it in for something like that (bad practice, I know ;))

Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘Back End’ is closed to new topics and replies.