I've been testing out some forms I've been building and I recently implemented token comparison for additional security. Here is the code for the token comparison:
On the form itself:
session_start();
$token = md5(uniqid(mt_rand(), true));
$_SESSION["token"] = $token;
session_write_close();
Then on the processing form:
session_start();
$token = "";
$token = $_SESSION['token'];
unset($_SESSION['token']);
session_write_close();
if(empty($token)) {
echo htmlspecialchars('An error has occurred. Please resubmit.');
// header( "refresh:3; url=website" );
die();
}
if($_POST['token'] != $token) {
echo htmlspecialchars('An error has occurred. Please resubmit.');
// header( "refresh:3; url=website" );
die();
}
The token is stored in the form like so:
<input type="hidden" name="token" value="<?php echo $token;?>"/>
The first time I fill out the form and submit it I always get a token error. However after some testing I realized the problem only occurs when I first start the server (WAMP). After the first initial submission, everything seems to work just fine. Here are some test comparisons I've done:
So the main issue is: When I restart the server, the token comparison seems to fail. After the first initial submit of the form (which is the failure) everything seems to work fine until I exit the server and start it back up again. Why is this happening?
The code that I am using is a modified version of the code posted by @leeppowers in this thread: thread