Preventing Redundant Form Submissions on Refresh
In web application development, it's not uncommon to encounter situations where refreshing a page after form submission leads to unintended multiple submissions. This behavior can occur when the server-side code does not properly handle form submission processing.
Consider the following example where a form is intended to insert data into a database upon submission:
<?php if (isset($_POST['name'])) { // Database operation to insert $_POST['name'] echo "Operation Done"; die(); } ?> <form action='page.php' method='post' name="myForm"> <input type="text" maxlength="50" name="name" class="input400" /> <input type="submit" name="Submit" /> </form>
After submitting the form, the data is successfully inserted into the database and the message "Operation Done" is displayed. However, if the page is subsequently refreshed, the form submission is repeated, resulting in the data being inserted again.
Solution: Redirect After Successful Form Submission
To avoid this problem, it's essential to redirect to another page after successfully processing the form submission. This ensures that when the page is refreshed, it's the new page that is being loaded, not the same form submission page.
Example with Redirect:
<?php if (isset($_POST['name'])) { // Database operation to insert $_POST['name'] header('Location: /path/to/record'); exit; } ?>
By adding the header redirection, the code ensures that after the database operation is complete, a redirect occurs to a new path. If the user refreshes the page, they will be directed to the new path instead of the form submission page.
Benefits of Redirecting:
The above is the detailed content of How to Prevent Form Submissions from Being Repeated on Refresh?. For more information, please follow other related articles on the PHP Chinese website!