Home > Backend Development > PHP Tutorial > How to Prevent Multiple Click Form Submission in PHP Using Unique Tokens?

How to Prevent Multiple Click Form Submission in PHP Using Unique Tokens?

Barbara Streisand
Release: 2024-11-12 06:23:02
Original
534 people have browsed it

How to Prevent Multiple Click Form Submission in PHP Using Unique Tokens?

Multiple Click Form Submission Prevention in PHP

In web applications, preventing multiple form submissions can enhance user experience and data integrity. PHP offers a solution to address this issue.

Solution: Unique Token

PHP utilizes unique tokens, generated each time a form is displayed. This token can be used only once. Implementing a token system not only prevents multiple form submissions but also safeguards against Cross-Site Request Forgery (CSRF) and replay attacks.

Implementation Example:

<?php
session_start();

// Function to create a unique token
function getToken() {
  $token = sha1(mt_rand());
  $_SESSION['tokens'][$token] = 1;
  return $token;
}

// Function to validate a token
function isTokenValid($token) {
  if (isset($_SESSION['tokens'][$token])) {
    unset($_SESSION['tokens'][$token]);
    return true;
  }
  return false;
}

// Check if a form has been submitted
$postedToken = filter_input(INPUT_POST, 'token');
if ($postedToken) {
  if (isTokenValid($postedToken)) {
    // Process form
  } else {
    // Handling for invalid token
  }
}

// Generate a token for the displayed form
$token = getToken();
?>

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

Additional Considerations:

  • Combine the token system with a redirect after form submission to maintain expected browser behavior.
  • Refer to the POST / redirect / GET pattern for more information on proper form handling.

By implementing this token-based solution, PHP developers can effectively prevent multiple form submissions, ensuring data integrity and enhancing user experience.

The above is the detailed content of How to Prevent Multiple Click Form Submission in PHP Using Unique Tokens?. 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