← Back to all snippets
PHP

Generate and Validate CSRF Tokens in PHP

Implement robust Cross-Site Request Forgery (CSRF) protection in your PHP applications using securely generated and validated anti-CSRF tokens for forms.

<?php
session_start();

// --- CSRF Token Generation ---
/**
 * Generates a unique CSRF token and stores it in the session.
 * @return string The generated CSRF token.
 */
function generateCsrfToken() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); // 32 bytes = 64 hex characters
    }
    return $_SESSION['csrf_token'];
}

// --- CSRF Token Validation ---
/**
 * Validates a submitted CSRF token against the one stored in the session.
 * @param string $token The token submitted by the user.
 * @return bool True if tokens match, false otherwise.
 */
function validateCsrfToken($token) {
    if (!isset($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $token)) {
        return false;
    }
    // Token is valid, clear it to prevent reuse (optional, but good for single-use tokens)
    unset($_SESSION['csrf_token']);
    return true;
}

// Example Usage:

// 1. On a form page (e.g., login.php, edit_profile.php)
// Generate a token and embed it in a hidden input field.
$csrfToken = generateCsrfToken();
?>
<!-- HTML Form Example -->
<form action="process.php" method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($csrfToken); ?>">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">
    <button type="submit">Submit</button>
</form>

<?php
// 2. On the processing page (e.g., process.php)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $submittedToken = $_POST['csrf_token'] ?? '';

    if (validateCsrfToken($submittedToken)) {
        // Token is valid, proceed with processing the form data
        echo "Form submitted securely. Processing data...";
        // ... process $_POST data ...
    } else {
        // Invalid CSRF token, reject the request
        http_response_code(403); // Forbidden
        die("CSRF token validation failed. Request blocked.");
    }
}
?>
How it works: This PHP snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection. CSRF tokens are unique, unpredictable values generated on the server for each user session and embedded in forms. When a form is submitted, the server validates the submitted token against the one stored in the user's session. This ensures that the request originated from a legitimate form on your site, preventing attackers from tricking users into submitting malicious requests from another domain. The `hash_equals()` function is used for constant-time comparison, mitigating timing attacks.

Need help integrating this into your project?

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

Hire DigitalCodeLabs