Home  >  Article  >  Backend Development  >  Understand the principles of anti-shaking and anti-resubmission in PHP

Understand the principles of anti-shaking and anti-resubmission in PHP

WBOY
WBOYOriginal
2023-10-12 09:15:53662browse

理解 PHP 中的防抖和防重复提交的原理

PHP is a programming language widely used for server-side development with powerful features and flexibility. In actual development, we often encounter scenarios where we need to prevent repeated submissions or anti-shake. This article will explore the principles of anti-shaking and anti-resubmission in PHP and provide specific code examples.

1. The principle of anti-shake

Anti-shake refers to the technology that prevents continuous triggering. It is often used to optimize the user experience and reduce unnecessary requests or operations. In PHP, we can implement anti-shake through JavaScript or Ajax calls.

  1. Principle

The principle of anti-shake is very simple, that is, only the last time an event is triggered multiple times within a certain period of time. For example, the real-time search function of a search box will trigger a search request every time the user enters a letter. Such frequent requests will put a lot of pressure on the server, and the user experience will not be good. Through anti-shake technology, we can set a time threshold and only send requests after the user stops inputting for a period of time to avoid frequent requests.

  1. Code Example

The following is a simple PHP code example that demonstrates how to use anti-shake technology:

<?php
function debounce($callback, $delay) {
    static $lastCallTime = 0;
    
    if (time() - $lastCallTime < $delay) {
        return;
    }
    
    $lastCallTime = time();
    call_user_func($callback);
}

function search() {
    // 假设这里是搜索功能的代码
    // ...
    echo "搜索结果";
}

// 假设这里是输入框的事件处理代码
input.addEventListener('input', function() {
    debounce(search, 500);
});
?>

In the above code, debounce The function accepts a callback function and delay time, and implements the anti-shake function by comparing the difference between the current time and the last trigger time. Each time an event is triggered, first determine whether the time difference between the two triggers is greater than the set delay time. If so, execute the callback function.

2. Principle of anti-duplicate submission

Anti-duplicate submission means preventing users from submitting the same data multiple times when submitting a form or request to ensure the uniqueness and correctness of the data. In PHP, we can use some technical means to prevent users from repeated submissions.

  1. Principle

The common principle to prevent repeated submission is to use Token or Session for verification. When the user submits the form, the server generates a unique Token and stores it in the Session or returns it to the client as a hidden field of the form. When the server receives a request submitted by a user, it first verifies the validity of the Token. If the Token has already been used or does not comply with the rules, it refuses to process it. This way we prevent users from submitting the same request repeatedly.

  1. Code Example

The following is a simple PHP code example that demonstrates how to use Token technology to prevent repeated submissions:

<?php
session_start(); // 开启 Session

function generateToken() {
    $token = md5(uniqid(rand(), true));
    $_SESSION['token'] = $token;
    return $token;
}

function checkToken($token) {
    if (!isset($_SESSION['token']) || $_SESSION['token'] !== $token) {
        return false;
    }
    $_SESSION['token'] = null; // 使用过的 Token 置空,避免重复使用
    return true;
}

function submitForm() {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        return;
    }
    
    $token = isset($_POST['token']) ? $_POST['token'] : '';
    if (checkToken($token)) {
        // 处理表单提交的逻辑
        // ...
        echo "表单提交成功";
    } else {
        echo "表单重复提交";
    }
}

// 生成 Token 并放入隐藏字段
$token = generateToken();
echo "<form method='post' action=''>";
echo "<input type='hidden' name='token' value='$token'>";
echo "<input type='submit' value='提交'>";
echo "</form>";

submitForm();
?>

In the above code , generateToken function is used to generate a unique Token and store it in the Session. checkToken The function is used to verify whether the submitted Token is valid. When the form is submitted, a Token is first generated and placed in the hidden field, and then the validity of the Token is verified on the server side.

Summary:

Through the above code examples, we can clearly understand the principles and implementation methods of anti-shaking and anti-duplicate submission in PHP. Anti-shaking and anti-repetitive submission are common requirements in actual development. Reasonable technical means can improve user experience and protect the uniqueness and correctness of data. In practical applications, we can choose appropriate anti-shake and anti-resubmission technical means according to specific scenarios.

The above is the detailed content of Understand the principles of anti-shaking and anti-resubmission in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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