PHP

Implementing CSRF Protection with Synchronizer Tokens in PHP

Secure your PHP web applications against Cross-Site Request Forgery (CSRF) attacks by generating and validating synchronizer tokens with this essential snippet.

<?php
// Start or resume a session
session_start();

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

// Function to validate a CSRF token
function validateCsrfToken($token) {
    if (isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token)) {
        return true;
    }
    return false;
}

// Example usage:

// On a form page, generate and embed the token
$csrfToken = generateCsrfToken();
echo '<form action="process.php" method="post">';
echo '<input type="hidden" name="_csrf" value="' . htmlspecialchars($csrfToken) . '">';
echo '<input type="text" name="data">';
echo '<button type="submit">Submit</button>';
echo '</form>';

// In process.php, validate the token
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['_csrf']) || !validateCsrfToken($_POST['_csrf'])) {
        die('CSRF token validation failed.');
    }
    // Token is valid, process the request
    echo 'Request processed successfully with valid CSRF token!';
    // Optionally, regenerate token after successful submission to prevent replay attacks on the same form (single-use token)
    // unset($_SESSION['csrf_token']); // For single-use token per form submission
    // generateCsrfToken(); // To ensure a new token for subsequent forms
}
?>
How it works: This snippet demonstrates how to implement CSRF (Cross-Site Request Forgery) protection in PHP using synchronizer tokens. A unique token is generated and stored in the user's session. This token is then embedded into forms as a hidden field. When the form is submitted, the server validates the submitted token against the one stored in the session using `hash_equals()` for timing attack safety. If they don't match, the request is rejected, preventing an attacker from tricking a logged-in user 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