PHP

Implement CSRF Protection with Tokens

Protect your web forms from Cross-Site Request Forgery (CSRF) attacks by generating and validating unique tokens with each form submission.

<?php
session_start();

// Generate a new token if not already set or regenerate on page load
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
$csrf_token = $_SESSION['csrf_token'];

// --- Form Display --- 
echo '<form action="process.php" method="POST">';
echo '<input type="hidden" name="csrf_token" value="' . $csrf_token . '">';
echo '<label for="data">Data:</label>';
echo '<input type="text" id="data" name="data">';
echo '<button type="submit">Submit</button>';
echo '</form>';

// --- Process Submission (e.g., in process.php) ---
/*
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        die('CSRF token mismatch!');
    }
    // Token is valid, process data
    echo "Data processed securely!";
    
    // Regenerate token after successful submission to prevent replay attacks
    unset($_SESSION['csrf_token']);
}
*/
?>
How it works: This code illustrates basic CSRF protection. A unique, cryptographically secure token is generated and stored in the user's session. This token is then embedded as a hidden field in forms. Upon form submission, the submitted token is compared against the one stored in the session. If they don't match, the request is rejected, 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