Page 1 of 1

Php - Help with Forms

Posted: Sun Dec 14, 2008 12:32 pm
by salitra
I need some help building a function that will detect whether a user has submitted multiple forms simultaneously (usually milliseconds apart). If the multiple submissions are successful usually it processes the second before the first can update the database. I want to be able to kill the second submission so that it doesn't get processed. I would be very grateful to anyone who could point me in the right direction :)

Thanks.

Re: Php - Help with Forms

Posted: Sun Dec 14, 2008 12:50 pm
by SteveC
If you are using PHP sessions, only one script will be able to use the session at once. Therefore, in a process such as this, you have the chance to save a session variable telling you that the form has been processed.

On each form you could paste a random MD5 code:

Code: Select all

<input type="hidden" name="formmd5" value="<?php echo md5(rand(1000000,9999999)); ?>">
And when the form submits, the handling script could create a session variable to mark the form as processed. Ie:

Code: Select all

$_SESSION['form_'.$_POST['formmd5']]=true;
Therefore, to check and see if the form has been processed:

Code: Select all

// has session code variable been set?
if (isset($_SESSION['form_'.$_POST['formmd5']])) {
  // form has already been processed.
  header('location: confirmation.php');
  exit;
}
 
// otherwise we are okay to process
 
You could even make the session variable an array if you want to include details about how the script was processed and the results it came up with. :)

Re: Php - Help with Forms

Posted: Sun Dec 14, 2008 12:52 pm
by SteveC
I should note you can do the same thing with an SQL table, ie:

Code: Select all

$query='INSERT INTO `form_codes` (code) VALUES ("'.$formcode.'")';
mysql_query($query,$db);
if (mysql_affected_rows($db)==1) {
  // form has not been submitted, so we're okay
} else {
  // form has already been submitted.
}
The 'code' field would need to have a UNIQUE or PRIMARY index for this to work.