paul
paul

Reputation: 741

Unset session variable not working when preventing double submissions

I am trying preventing a user double submitting a form if they click the button twice using the below code.

// Check token is present
if (!isset($_POST['token'])) {
    // Token missing
    exit();
}

// Check token matches session value
if ($_POST['token'] != $_SESSION['token']) {
    // Token mismatch
    exit();
}

// Valid submission - Invalidate token
unset($_SESSION['token']);


// Make payment
$result = makePayment(); // cURL request to api

The problem is that unset($_SESSION['token']) doesn't seem to be working. On the 2nd request, the token is still in the session. I think it's because the session value is not getting cleared before the next submission.

In this resepnse to a similar question: https://stackoverflow.com/a/1025919/1587851 session_write_close() is suggested and I think adding it after my unset is working, but I don't really understand what it does:

// Valid submission - Invalidate token
unset($_SESSION['token']);
session_write_close();

Two questions:

  1. Is there any problems with this solution?
  2. Can I still get and set session variables after calling session_write_close()?

Thanks.

Might be relevant, I'm using ADOdb to store session data in the database

Upvotes: 1

Views: 414

Answers (1)

David Ansermot
David Ansermot

Reputation: 6112

Try to do :

$_SESSION['token'] = null;

Sometimes, the unset() is not effective immediatly.

Upvotes: 0

Related Questions