PHP Session Tokens for form security
<p>I have not been able to successfully submit a form I am working on in Chrome or Firefox. The form works in Safari, however. </p>

<p>I just started trying to use PHP last week and modified code from this <a href="https://css-tricks.com/serious-form-security/" rel="nofollow">post</a> on CSS Tricks. I am trying to give the session a random token, store that token in a variable, set that token to a hidden input field, and then make sure the two match when the form is submitted.</p>

<p>The problem is that the session token that is created doesn't match the token assigned as a value to the hidden input. When the form is submitted, a new session token is recreated and thus doesn't match the original random number from the session. The curious thing is that it works in Safari and not other browsers. </p>

<p>The PHP</p>

<pre><code>&lt;?php 
session_start();

function generateFormToken($form) {

    // generate a token from an unique value, took from microtime, you can also use salt-values, other crypting methods...
    $token = md5(uniqid(microtime(), true));  

    // Write the generated token to the session variable to check it against the hidden field when the form is sent
    $_SESSION[$form.'_token'] = $token; 
    echo $token;
    return $token;
}

function verifyFormToken($form) {

    // check if a session is started and a token is transmitted, if not return an error
    if(!isset($_SESSION[$form.'_token'])) { 
        return false;
    }

    // check if the form is sent with token in it
    if(!isset($_POST['token'])) {
        return false;
    }

    // compare the tokens against each other if they are still the same
    if ($_SESSION[$form.'_token'] !== $_POST['token']) {
        return false;
    }

    return true;
}
function check_input($data)
{
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
  }

if (verifyFormToken('form1')) {
    $name = check_input($_POST["name"]);
    $email = check_input($_POST["emailaddress"]);
    $message = check_input($_POST["message"]);
    $ForwardTo = 'me@gmail.com';
    $details='Name: '.$name."\n".'Email: '.$email."\n".'Message: '.$message."\n";

        //do stuff
    mail($ForwardTo,"Construction of Hope Contact",$details,"From:$email");
}

?&gt;
</code></pre>

<p>The related form:</p>

<p><div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!--Markup for Contact form--&gt;
  &lt;form action='index.php' method='post' class='contact-format'&gt;


  &lt;p&gt;&lt;input type="hidden" name="token" value="&lt;?php echo $newToken; ?&gt;"&gt;&lt;/p&gt;
  &lt;p&gt;
      &lt;button type="submit" name='submit' class="btn btn-primary button"&gt;Send&lt;/button&gt;
    &lt;/p&gt;</code></pre>
</div>
</div>
</p>