How to prevent multiple inserts when submitting a form in PHP?

PHP provides several methods to prevent multiple inserts when users accidentally submit forms multiple times. The most common approaches include using sessions with timestamps, CSRF tokens, and database constraints.

Method 1: Using Session Timestamps

This method tracks the last form submission time to prevent duplicate submissions within a specified time window −

<!-- form.html -->
<form action="process_form.php" method="post">
    <input type="text" name="username" placeholder="Enter username" required>
    <input type="email" name="email" placeholder="Enter email" required>
    <input type="submit" value="Submit">
</form>
<?php
// process_form.php
session_start();

if (isset($_POST['username']) && isset($_POST['email'])) {
    // Check if form was recently submitted
    if (isset($_SESSION['posttimer'])) {
        $timeDiff = time() - $_SESSION['posttimer'];
        if ($timeDiff <= 3) {
            echo "Please wait before submitting again. Time remaining: " . (3 - $timeDiff) . " seconds";
            exit;
        }
    }
    
    // Process form data here
    echo "Form submitted successfully for: " . htmlspecialchars($_POST['username']);
    
    // Update session timer
    $_SESSION['posttimer'] = time();
} else {
    echo "Invalid form submission";
}
?>

Method 2: Using CSRF Tokens

This approach generates unique tokens for each form to ensure single−use submissions −

<?php
// form_with_token.php
session_start();

// Generate CSRF token
if (!isset($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<form action="process_token.php" method="post">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    <input type="text" name="message" placeholder="Enter message" required>
    <input type="submit" value="Submit">
</form>
<?php
// process_token.php
session_start();

if (isset($_POST['csrf_token']) && isset($_POST['message'])) {
    // Verify CSRF token
    if ($_POST['csrf_token'] === $_SESSION['csrf_token']) {
        // Process the form
        echo "Message received: " . htmlspecialchars($_POST['message']);
        
        // Regenerate token to prevent resubmission
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    } else {
        echo "Invalid token. Please refresh the form.";
    }
} else {
    echo "Invalid request";
}
?>

Method 3: JavaScript Prevention

Client−side prevention using JavaScript to disable submit button after clicking −

<form action="process_form.php" method="post" onsubmit="return preventMultipleSubmit()">
    <input type="text" name="data" placeholder="Enter data" required>
    <input type="submit" id="submitBtn" value="Submit">
</form>

<script>
function preventMultipleSubmit() {
    const submitBtn = document.getElementById('submitBtn');
    submitBtn.disabled = true;
    submitBtn.value = 'Processing...';
    return true;
}
</script>

Comparison

Method Security Level User Experience Implementation
Session Timestamps Medium Good Simple
CSRF Tokens High Excellent Moderate
JavaScript Prevention Low Good Simple

Conclusion

For maximum security, combine CSRF tokens with session timestamps. The JavaScript method provides good user experience but should not be the only protection method since it can be bypassed.

Updated on: 2026-03-15T08:54:03+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements