Last updated on November 21, 2022
In this post, we gonna see how we can prevent multiple submissions of a form in PHP applications.
Sometimes a user may hit submit button twice or the user may reload the page(with post data), both activities make form processing multiple times with the same data, which results in duplicate records in DB or duplicate Emails in the Inbox.
In order to avoid this behavior in PHP, we will include a unique token on each post request this method is also useful to prevent CSRF and replay attacks. we will include generated unique key in the form, hidden field, and session variable. Once the form is submitted we will compare the hidden field value with the session token value, if both values match the form submission is valid, if the token does not match the token in your session, the form has been re-submitted.
How to generate a token
In this example, the PHP function uniqid()
is used to generate the form token value.
<?php
// start the session
session_start();
// form token
$form_token = uniqid();
// create form token session variable and store generated id in it.
$_SESSION['form_token'] = $form_token;
?>
Show me the Logic
just copy the above code and past it to the form page. then create a hidden field inside the form as shown below
<input name="token" type="hidden" value="<?php echo $form_token; ?>">
In the form process page, we will compare the token as shown below
if($_POST['form_token'] != $_SESSION['form_token']) {
echo 'form resubmitted!'; exit;
} else {
do ...
}
Complete Example
Below is the completed sample script for preventing multiple form submissions in PHP.
<?php
/*** begin the session ***/
session_start();
/*** create the form token ***/
$form_token = uniqid();
/*** add the form token to the session ***/
$_SESSION['form_token'] = $form_token;
?>
<!DOCTYPE html>
<head>
<title>My Form</title>
</head>
<body>
<form action="process.php" method="post">
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<div>
<label for="name">Name</label>
<input type="text" name="name" />
<div>
<div>
<input type="submit" value="Add Name" />
</div>
</form>
</body>
</html>
Create process.php
file and place the below code in it.
<?php
//process.php
// start session
session_start();
if($_POST['form_token'] != $_SESSION['form_token'])
{
echo 'Access denied';
} else {
print_r($_POST);
// do your logic
}
$_SESSION['form_token'] = "";
I hope it helps you guys to prevent multiple form submissions.
Do share it and let your friends know about it.