title: Preventing duplicate form submissions
body: <p>I came up with a technique to prevent duplicate form submission by going back/forward or refreshing the page. And I thought about duscussing it here, I already tested a sample not in production environment, what is flaws that you can identify?</p>
  
  <p>Please note that I am well aware of using Form Tokens, which will defend you against CSRF attacks, and wasn't added in the steps below. </p>
  
  <p>-Generate Form ID for each form, and use it as hidden field in the form:</p>
  
  <pre><code>$formid = microtime(true)*10000;
  </code></pre>
  
  <p>-<strong>On form submit</strong>: </p>
  
  <ul>
  <li><p>Validate from data</p></li>
  <li><p>Calculate the hash of form fields data</p>
  
  <pre><code>$allvals = '';
  foreach($_POST as $k=&gt;$v){
      $allvals .= $v;
  }
  $formHash = sha1($allvals);
  </code></pre></li>
  <li><p>Validate form hash by comparing with previously saved hashes. the session value is binded to each form by $formid variable.</p>
  
  <pre><code>$allowAction = true;
  if(isset($_SESSION['formHash'][$_POST['formid']]) &amp;&amp; ($_SESSION['formHash'][$_POST['formid']] == $formHash)){
       $allowAction = false;
  }
  </code></pre></li>
  <li>if form hash wasn't found, it means this is the first time form submitted or the form data is changed. </li>
  <li><p>If data saved ( to database, for example), save form hash to session:</p>
  
  <pre><code>$_SESSION['formHash'][$_POST['formid']] = $formHash;
  </code></pre></li>
  </ul>
  
  <p>Full version of the code:
  <a href="http://thebusy.me/2011/01/06/preventing-duplicate-form-submissions/">http://thebusy.me/2011/01/06/preventing-duplicate-form-submissions/</a></p>