PHP

Implementing Anti-CSRF Protection with Synchronizer Tokens in PHP

Protect web forms and state-changing actions from Cross-Site Request Forgery (CSRF) attacks. Generate and validate unique synchronizer tokens for each user session in PHP, ensuring legitimate user intent.

<?php
session_start(); // Start the session to store and retrieve the token

// Function to generate a new CSRF token
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // Generate a secure random token
    }
    return $_SESSION['csrf_token'];
}

// Function to validate the submitted CSRF token
function validateCsrfToken($token) {
    if (!isset($_SESSION['csrf_token']) || $token !== $_SESSION['csrf_token']) {
        return false; // Token mismatch or missing
    }
    // Token is valid, invalidate it to prevent reuse (optional, but good practice for single-use forms)
    // unset($_SESSION['csrf_token']);
    return true;
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submittedToken = $_POST['csrf_token'] ?? '';

    if (validateCsrfToken($submittedToken)) {
        echo "Form submitted successfully! CSRF token is valid.<br>";
        // Process the form data safely here
        // Example: update database, change user settings, etc.
    } else {
        echo "Error: Invalid CSRF token. Request blocked.<br>";
        // Log the attempt, redirect, or show an error
        http_response_code(403); // Forbidden
        exit;
    }
}

// Generate token for the form (or subsequent requests)
$csrfToken = generateCsrfToken();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSRF Protection Example</title>
</head>
<body>
    <h1>Submit Data Securely</h1>

    <form action="" method="post">
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
        <label for="data">Your Message:</label>
        <input type="text" id="data" name="message" required>
        <button type="submit">Send</button>
    </form>

    <p>
        This form includes a CSRF token. Try submitting the form directly (e.g., via a browser extension that blocks referrers or manipulates requests) and then remove the token to see the protection in action.
    </p>
</body>
</html>
How it works: Cross-Site Request Forgery (CSRF) attacks trick authenticated users into executing unwanted actions on a web application. This PHP snippet implements a common and effective defense mechanism: synchronizer tokens. A unique, unpredictable token is generated and stored in the user's session, then embedded as a hidden field in forms. Upon submission, the server verifies if the submitted token matches the one in the session. A mismatch indicates a potential CSRF attack, blocking the request and ensuring that all state-changing actions are initiated by the legitimate user.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs