Php - Help with Forms

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
salitra
Forum Newbie
Posts: 1
Joined: Sun Dec 14, 2008 12:24 pm

Php - Help with Forms

Post 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.
SteveC
Forum Commoner
Posts: 44
Joined: Thu Dec 04, 2008 2:39 pm
Location: Lansing, MI

Re: Php - Help with Forms

Post 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. :)
SteveC
Forum Commoner
Posts: 44
Joined: Thu Dec 04, 2008 2:39 pm
Location: Lansing, MI

Re: Php - Help with Forms

Post 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.
Post Reply