Prevent Duplicate Form Submission

Prevent Duplicate Form Submission
Learn how to use PHP sessions to prevent duplicate form submission or re-submission.

You can use the method below to prevent duplicate form submission or form re-submission using PHP. This method is simple to implement and does not require JavaScript.
I will assume that the form is in the form.php file and the form submission is being handled by the form-exec.php script.

Modifying your form

Add this PHP code to the top of the form.php script:

<?
session_start();
$secret=md5(uniqid(rand(), true));
$_SESSION['FORM_SECRET']=$secret;
?>

In the PHP code above we create a unique ID using the uniqid() function and then create a 32 character hash of this unique ID using md5() function. Next we store this unique ID in the session for later use in the form-exec.php script. Remember to use a different session variable for each form.

Then add a hidden field anywhere in your form:

<html>
<input type="hidden" name="form_secret" id="form_secret" value="<?php echo $_SESSION['FORM_SECRET'];?>" />
</html>

Handling form submission

Compare the value of the hidden field with the value stored in the session. If the values match, process the form data. After processing the form data unset the value stored in the session. Now if the user refreshes the page, the form processing code will be skipped. See the sample code below.

<?
//Retrieve the value of the hidden field
$form_secret=$_POST['form_secret'];
if(isset($_SESSION['FORM_SECRET'])) {
if(strcasecmp($form_secret,$_SESSION['FORM_SECRET'])===0) {
/*Put your form submission code here
After processing the form data,
unset the secret key from the session
*/
unset($_SESSION['FORM_SECRET']);
}else {
//Invalid secret key
}
}else {
//Secret key missing
echo 'Form data has already been processed!';
}
?>
Nathan Pakovskie is an esteemed senior developer and educator in the tech community, best known for his contributions to Geekpedia.com. With a passion for coding and a knack for simplifying complex tech concepts, Nathan has authored several popular tutorials on C# programming, ranging from basic operations to advanced coding techniques. His articles, often characterized by clarity and precision, serve as invaluable resources for both novice and experienced programmers. Beyond his technical expertise, Nathan is an advocate for continuous learning and enjoys exploring emerging technologies in AI and software development. When he’s not coding or writing, Nathan engages in mentoring upcoming developers, emphasizing the importance of both technical skills and creative problem-solving in the ever-evolving world of technology. Specialties: C# Programming, Technical Writing, Software Development, AI Technologies, Educational Outreach

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top