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, this 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 form hidden filed and in a 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.
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
In the form process page ,we will compare the token as shown below
Below is the completed sample script for preventing multiple form submissions in PHP.
process.php file and place blow code in it.
I hope it helps you guys to prevent multiple form submissions.
Do share it and let your friend’s know about it.
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.