Home > Backend Development > PHP Tutorial > How Can I Prevent Unintended Form Resubmission in Web Applications?

How Can I Prevent Unintended Form Resubmission in Web Applications?

Susan Sarandon
Release: 2024-11-13 00:43:02
Original
553 people have browsed it

How Can I Prevent Unintended Form Resubmission in Web Applications?

Preventing Unintended Form Resubmission

Form resubmission due to page refresh is a common annoyance in web applications. To handle this issue effectively, it's crucial to employ the following strategies:

Redirect After Submission

Instead of displaying the response on the same page, redirect the user to a separate page once the form is submitted. This ensures that when the refreshed page loads, it's a new GET request and not a repeat of the POST request that has already been processed.

Example:

// submit
// set success flash message (you are using a framework, right?)
header('Location: /path/to/record');
exit;
Copy after login

Disable Browser Caching

To prevent the browser from caching your form, add the following headers to your PHP script:

header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
Copy after login

Unique Page Token

Generate a unique token on the server for each form submission. Include this token as a hidden field in the form and verify it before processing. If the token doesn't match or is missing, discard the request as a duplicate submission.

Example (with session token):

<?php
session_start();

// Generate a unique token and store it in the session
$token = md5(uniqid(mt_rand(), true));
$_SESSION['token'] = $token;

?>

<!DOCTYPE html>
<html>
<body>

<form action="submit.php" method="post">
  <input type="text" name="name">
  <input type="hidden" name="token" value="<?php echo $token; ?>">
  <input type="submit" value="Submit">
</form>

</body>
</html>
Copy after login
<?php
session_start();

// Get the submitted token
$token = $_POST['token'];

// Check if the token matches the session token
if ($token != $_SESSION['token']) {
  // Discard the request
} else {
  // Process the form data
}
Copy after login

Conclusion

By implementing these techniques, you can effectively prevent unwanted form resubmissions due to page refresh and ensure that your web application behaves as intended.

The above is the detailed content of How Can I Prevent Unintended Form Resubmission in Web Applications?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template