[Huang Ah Code] How does PHP prevent repeated submissions

Anti-shaking (Debounce) is a strategy to prevent repeated submissions. It merges consecutive operations by delaying for a certain period of time to ensure that they are only executed once.

The following are several anti-shake implementation methods and corresponding code examples:

1. Front-end JavaScript implementation:
Use JavaScript to implement anti-shake at the front end, and you can use  setTimeout functions to delay the execution of submission operations.

function debounce(func, delay) {     let timer;     return function() {         clearTimeout(timer);         timer = setTimeout(() => {             func. apply(this, arguments);         }, delay);     }; } const submitForm = debounce(function() {     // perform form submission here }, 1000); // delay execution for 1 second











2. Backend PHP implementation (using Session):
Using Session at the backend can prevent repeated submissions. Before submitting, store a token in the Session, then verify that the tokens match after submitting.

session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {     $token = uniqid(); // Generate a unique token     $_SESSION['submit_token'] = $token;     // Perform form submission Operation     unset($_SESSION['submit_token']); // Clear token }






3. Backend PHP implementation (using Token):
Generate a unique Token each time the page is loaded and store it in the form. When the form is submitted, verify that the Token matches.

if ($_SERVER['REQUEST_METHOD'] === 'POST') {     $submittedToken = $_POST['token'];     $storedToken = $_SESSION['submit_token'];     if ($submittedToken === $storedToken) {         // Perform form submission operation         unset($_SESSION['submit_token']); // Clear token     } }







Note that the code sample above is a basic anti-shake method. In practical applications, you may need to make appropriate adjustments and extensions based on business needs. At the same time, in order to better prevent repeated submissions, the front-end and back-end methods can also be combined to ensure data security.

What are the implementation methods of PHP anti-shake (anti-duplicate submission), here are 10

Debounce is a commonly used method to prevent repeated submissions. It can ensure that only one submission operation is performed in a short period of time to avoid problems caused by repeated submissions. Here are 10 ways to achieve stabilization, each with a simple code example:

1 Session Token anti-shake:
use the token in the session (Session) to prevent repeated submissions.

// generate a random token
$token = md5(uniqid());

// store the token in the session
$_SESSION['submit_token'] = $token;

// embed the token in the form
echo '<input type="hidden" name ="submit_token" value="' . $token . '">';

// processing validation when submitting the form
if ($_POST['submit_token'] === $_SESSION['submit_token']) {     // processing Form submission     // clear token in session     unset($_SESSION['submit_token']); }



2 Token anti-shake:
Use randomly generated tokens to prevent repeated submissions.

$token = md5(uniqid());
echo '<input type="hidden" name="submit_token" value="' . $token . '">';

if ($_POST['submit_token'] === $token) {
    // 处理表单提交
}

3 Timestamp anti-shake:
Use timestamps to prevent repeated submissions within a period of time.

$currentTime = time();
$lastSubmitTime = $_SESSION['last_submit_time'] ?? 0;

if ($currentTime - $lastSubmitTime > 5) {
    // 处理表单提交
    $_SESSION['last_submit_time'] = $currentTime;
}

4 IP address anti-shake:
use IP address to prevent repeated submission of the same IP

$userIP = $_SERVER['REMOTE_ADDR'];
$lastSubmitIP = $_SESSION['last_submit_ip'] ?? '';

if ($userIP !== $lastSubmitIP) {     // Process form submission     $_SESSION['last_submit_ip'] = $userIP; }


5 Cookie anti-shake:
Use cookies to prevent repeated submissions within a period of time.

if (!isset($_COOKIE['submit_cookie'])) {     // Process form submission     setcookie('submit_cookie', 'submitted', time() + 60); // Do not allow repeated submissions within 60 seconds }


6 JavaScript anti-shake:
Use JavaScript to control the clickable state of the submit button to prevent repeated clicks.

<button id="submitBtn" οnclick="submitForm()">Submit</button>

<script>
    let submitting = false;

    function submitForm() {
        if (!submitting) {
            submitting = true;
            // 执行表单提交操作
            document.getElementById('submitBtn').disabled = true;
        }
    }
</script>

7 Delay anti-shake:
within a period of time after the last operation, only one commit operation is performed.

if (!isset($_SESSION['submit_timer'])) {     $_SESSION['submit_timer'] = time(); } if (time() - $_SESSION['submit_timer'] > 10) {     // handle form submission     $_SESSION['submit_timer'] = time(); }






8. Database uniqueness constraint:
Use the uniqueness constraint of the database to prevent repeated insertion of data.

try {     // try to insert data, if the insertion fails, an exception will be thrown     // add a unique index or unique constraint to the database to prevent duplicate data } catch (Exception $e) {     // handle the insertion failure }




9 Cache anti-shake:
Use the cache system to record the submission status.

$cacheKey = 'submit_status_' . $userIP;
if (!cache_get($cacheKey)) {     // process form submission     cache_set($cacheKey, 'submitted', 60); // do not allow repeated submission within 60 seconds }


10 Verification code anti-shake:
Require users to enter a specific verification code to submit the form to prevent malicious repeated submissions.

if ($_POST['captcha'] === $_SESSION['captcha_code']) {     // Process form submission     // Clear the captcha to prevent multiple use of the same captcha     unset($_SESSION['captcha_code'] ); }



These sample codes show different anti-shake methods, and you can choose the appropriate method according to your needs to prevent duplicate submissions. Please note that these methods may need to be properly adjusted and optimized according to your specific application scenarios.

Guess you like

Origin blog.csdn.net/TiaoZhanJi_Xian/article/details/132707423