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?
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.
-Generate Form ID for each form, and use it as hidden field in the form:
$formid = microtime(true)*10000;
-On form submit:
Validate from data
Calculate the hash of form fields data
$allvals = ''; foreach($_POST as $k=>$v){ $allvals .= $v; } $formHash = sha1($allvals);
Validate form hash by comparing with previously saved hashes. the session value is binded to each form by $formid variable.
$allowAction = true; if(isset($_SESSION['formHash'][$_POST['formid']]) && ($_SESSION['formHash'][$_POST['formid']] == $formHash)){ $allowAction = false; }
- if form hash wasn't found, it means this is the first time form submitted or the form data is changed.
If data saved ( to database, for example), save form hash to session:
$_SESSION['formHash'][$_POST['formid']] = $formHash;
Full version of the code: http://thebusy.me/2011/01/06/preventing-duplicate-form-submissions/