PHP

Implement CSRF Protection with Synchronizer Tokens in PHP

Secure web forms against Cross-Site Request Forgery (CSRF) attacks by generating and validating unique synchronizer tokens for each user session.

<?php
session_start();

// Generate CSRF token
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Validate CSRF token
function validateCsrfToken($token) {
    if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
        // Log this attempt and potentially deny access
        error_log("CSRF token mismatch detected.");
        return false;
    }
    // Token is valid, clear it for one-time use or rotate it
    // unset($_SESSION['csrf_token']); // For one-time use tokens
    return true;
}

// Example usage in a form:
// <form action="/process.php" method="POST">
//     <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars(generateCsrfToken()); ?>">
//     <!-- other form fields -->
//     <button type="submit">Submit</button>
// </form>

// Example usage in process.php:
/*
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !validateCsrfToken($_POST['csrf_token'])) {
        die('CSRF token validation failed.');
    }
    // Process form data securely
}
*/
?>
How it works: This snippet demonstrates how to implement CSRF protection using synchronizer tokens in PHP. A unique token is generated and stored in the user's session. This token is then embedded into forms as a hidden field. Upon form submission, the submitted token is compared against the one stored in the session. If they don't match, the request is considered malicious and blocked, preventing attackers from forging requests on behalf of authenticated users.

Need help integrating this into your project?

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

Hire DigitalCodeLabs