PHP

Secure Forms with CSRF Protection

Learn to implement robust CSRF protection in PHP web applications using synchronized tokens, preventing unauthorized cross-site request forgery attacks on user actions.

<?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 the attempt, destroy session, or redirect
        // For production, a more robust error handling is needed
        die('CSRF token validation failed.');
    }
    return true;
}

// --- Example Usage ---

// On a page displaying a form (e.g., index.php)
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $csrfToken = generateCsrfToken();
    echo "<form action='process.php' method='POST'>
";
    echo "    <input type='text' name='data' placeholder='Enter data'>
";
    echo "    <input type='hidden' name='csrf_token' value='" . htmlspecialchars($csrfToken) . "'>
";
    echo "    <button type='submit'>Submit</button>
";
    echo "</form>
";
}

// In a processing script (e.g., process.php)
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['csrf_token'])) {
        validateCsrfToken($_POST['csrf_token']);
        // If validation passes, process the form data
        echo "Form processed successfully! Data: " . htmlspecialchars($_POST['data']);
        // It's good practice to regenerate the token after successful use or for each form submission
        // unset($_SESSION['csrf_token']); // or $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    } else {
        die('CSRF token missing.');
    }
}
?>
How it works: This snippet demonstrates how to implement Cross-Site Request Forgery (CSRF) protection using synchronized tokens in PHP. A unique token is generated and stored in the user's session, then embedded in forms as a hidden field. Upon form submission, the submitted token is compared against the one in the session. If they don't match, the request is rejected, preventing malicious sites from tricking users into performing unwanted actions.

Need help integrating this into your project?

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

Hire DigitalCodeLabs