SoFunction
Updated on 2025-03-10

How to prevent duplicate submissions from PHP

Debounce is a strategy to prevent repeated submissions, which merges continuous operations by delaying a certain amount of time to ensure that they are performed only once.

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

1. Front-end JavaScript implementation

Using JavaScript to implement anti-shake on the front end, you can use the setTimeout function to delay the execution of the submission operation.

function debounce(func, delay) {
    let timer;
    return function() {
        clearTimeout(timer);
        timer = setTimeout(() => {
            (this, arguments);
        }, delay);
    };
}
​​​​​​​const submitForm = debounce(function() {
    // Perform the form submission operation here}, 1000); // Delay 1 Execute in seconds

2. Backend PHP implementation (using Session)

Using Session on the backend prevents duplicate submissions. Before committing, store a token in the Session and then verify that the token matches after committing.

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 every time the page loads 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    }
}

Please note that the above code example is the basic anti-shake method. In practical applications, you may need to make appropriate adjustments and expansions according to your business needs. At the same time, in order to better prevent duplicate submissions, a combination of front-end and back-end methods can also be used to ensure data security.

What are the implementation methods for PHP anti-shake (anti-repeated submissions), here are 10

Debounce is a commonly used method to prevent duplicate submissions. It ensures that only one submission operation is performed in a short period of time to avoid problems caused by duplicate submissions. Here are 10 ways to implement anti-shake, each with a simple code example:

1 Session Token Anti-shake

Use tokens in sessions to prevent duplicate submissions.

// Generate random tokens$token = md5(uniqid());
//Storage token to session$_SESSION['submit_token'] = $token;
// Embed token in formecho '<input type="hidden" name="submit_token" value="' . $token . '">';
​​​​​​​// Verification when processing form submissionif ($_POST['submit_token'] === $_SESSION['submit_token']) {
    // Process form submission    // Clear tokens in the session    unset($_SESSION['submit_token']);
}

2 Token anti-shake

Use randomly generated tokens to prevent duplicate submissions.

$token = md5(uniqid());
echo '<input type="hidden" name="submit_token" value="' . $token . '">';
​​​​​​​if ($_POST['submit_token'] === $token) {
    // Process form submission}

3 timestamp anti-shake

Use timestamps to prevent duplicate commits over a period of time.

$currentTime = time();
$lastSubmitTime = $_SESSION['last_submit_time'] ?? 0;
​​​​​​​if ($currentTime - $lastSubmitTime > 5) {
    // Process form submission    $_SESSION['last_submit_time'] = $currentTime;
}

4 IP address anti-shake

Use IP addresses to prevent duplicate submissions 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 Cookies Anti-shake

Use cookies to prevent duplicate submissions over a period of time.

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

6 JavaScript Anti-shake

Use JavaScript to control the clickable status of the submit button to prevent repeated clicks.

<button  οnclick="submitForm()">Submit</button>
<script>
    let submitting = false;
​​​​​​​    function submitForm() {
        if (!submitting) {
            submitting = true;
            // Perform form submission operation            ('submitBtn').disabled = true;
        }
    }
</script>

7 Delayed anti-shake

Only one commit operation is performed for a period of time after the last operation.

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

8 Database uniqueness constraints

Use database uniqueness constraints to prevent repeated insertion of data.

try {
    // Try to insert data, if the insert fails, an exception will be thrown    // Add unique index or uniqueness constraints of the database to prevent duplicate data} catch (Exception $e) {
    // Handle insertion failure}

9 Cache anti-shake

Use the cache system to record the commit status.

$cacheKey = 'submit_status_' . $userIP;
if (!cache_get($cacheKey)) {
    // Process form submission    cache_set($cacheKey, 'submitted', 60); // Repeated submissions are not allowed within 60 seconds}

10 verification code anti-shake

Users are required to enter a specific verification code to submit the form to prevent malicious and repeated submissions.

if ($_POST['captcha'] === $_SESSION['captcha_code']) {
    // Process form submission    // Clear the verification code to prevent the same verification code from being used multiple times    unset($_SESSION['captcha_code']);
}

These sample codes show different anti-shake methods, and you can choose the right method according to your needs to prevent duplicate submissions. Please note that these methods may require appropriate adjustments and optimizations based on your specific application scenario.

This is the article about how PHP can prevent duplicate submissions. For more related content related to PHP, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!