PHP

Implement CSRF Protection Using Synchronizer Tokens in PHP

Safeguard your web forms from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique, short-lived synchronizer tokens on the server-side with PHP.

<?php
session_start();

function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // Generate a random 64-character hex string
    }
    return $_SESSION['csrf_token'];
}

function validateCsrfToken($token) {
    if (empty($token) || empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
        // Token is missing, session token is missing, or tokens do not match
        return false;
    }
    // Optionally, regenerate token after successful validation to prevent replay (single-use token)
    // unset($_SESSION['csrf_token']);
    return true;
}

// --- Usage Example ---

// 1. On the page rendering the form:
$csrfToken = generateCsrfToken();
?>
<!DOCTYPE html>
<html>
<head><title>CSRF Example</title></head>
<body>
    <form action="process.php" method="POST">
        <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
        <label for="message">Message:</label>
        <input type="text" id="message" name="message" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>

<?php
// 2. In process.php (the form submission handler):
// if ($_SERVER['REQUEST_METHOD'] === 'POST') {
//     $submittedToken = $_POST['csrf_token'] ?? '';
//     if (validateCsrfToken($submittedToken)) {
//         echo "Form submitted securely! Message: " . htmlspecialchars($_POST['message']);
//         // Proceed with processing the form data
//     } else {
//         echo "CSRF token validation failed. Possible attack detected!";
//         // Handle error, log, redirect, etc.
//     }
// }
?>
How it works: This PHP snippet demonstrates a basic implementation of CSRF (Cross-Site Request Forgery) protection using synchronizer tokens. A unique token is generated and stored in the user's session (`$_SESSION`) and also embedded as a hidden field in the form. Upon form submission, the server validates if the submitted token matches the one in the session. This ensures that only requests originating from the legitimate application are processed, preventing malicious third-party sites from tricking users into executing unintended actions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs