How to Prevent Multiple Form Submissions with PHP?

Barbara Streisand
Release: 2024-11-09 14:26:02
Original
651 people have browsed it

How to Prevent Multiple Form Submissions with PHP?

Preventing Multiple Form Submissions with PHP

In web development, it's essential to safeguard against multiple form submissions when a user repeatedly clicks on the submit button. This can lead to unintended results, such as duplicate data entries or unexpected behavior. PHP offers several techniques to prevent this issue.

One effective approach is to utilize unique form tokens. When a form is displayed, a unique token is generated and stored in the session. When the form is submitted, the token is checked against the stored version. If the tokens match, the form submission is processed. If they don't, the submission is rejected, preventing multiple submissions.

Here's a simple PHP implementation:

session_start();

function getToken() {
  $token = sha1(mt_rand());
  if (!isset($_SESSION['tokens'])) {
    $_SESSION['tokens'] = array($token => 1);
  } else {
    $_SESSION['tokens'][$token] = 1;
  }
  return $token;
}

function isTokenValid($token) {
  if (!empty($_SESSION['tokens'][$token])) {
    unset($_SESSION['tokens'][$token]);
    return true;
  }
  return false;
}

$postedToken = filter_input(INPUT_POST, 'token');
if (!empty($postedToken)) {
  if (isTokenValid($postedToken)) {
    // Process form
  } else {
    // Handle error
  }
}

$token = getToken();
Copy after login
<form method="post">
  <fieldset>
    <input type="hidden" name="token" value="<?php echo $token; ?>" />
    <!-- Add form content -->
  </fieldset>
</form>
Copy after login

To enhance security, combine this token validation with a redirect on form submission. This ensures that when a user presses the back button, a new form is displayed with a fresh token. This pattern, known as POST / redirect / GET, further prevents multiple submissions and maintains backward and forward compatibility.

The above is the detailed content of How to Prevent Multiple Form Submissions with PHP?. 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