PHP

Implement CSRF Protection in PHP Forms

Prevent Cross-Site Request Forgery (CSRF) attacks in your web applications by generating and validating unique, time-sensitive tokens in PHP forms.

<?php
session_start();

// 1. Generate CSRF token if not exists or if a new one is needed
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

$csrf_token = $_SESSION['csrf_token'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($csrf_token, $_POST['csrf_token'])) {
        // CSRF token mismatch - potentially malicious request
        die('CSRF token validation failed. Request blocked.');
    }

    // If validation passes, process the form data securely
    $user_input = htmlentities($_POST['user_data'], ENT_QUOTES, 'UTF-8');
    echo "Form submitted successfully with data: " . $user_input . "<br>";
    // In a real application, you would now process $user_input (e.g., save to DB)

    // Optionally, regenerate the token after successful use to prevent replay attacks
    unset($_SESSION['csrf_token']);
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>CSRF Protection Example</title>
</head>
<body>
    <h2>Submit Data Securely</h2>
    <form method="POST" action="">
        <input type="hidden" name="csrf_token" value="<?php echo $csrf_token; ?>">
        <label for="user_data">Your Data:</label>
        <input type="text" id="user_data" name="user_data" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
How it works: This snippet demonstrates how to protect against Cross-Site Request Forgery (CSRF) attacks using a synchronizer token pattern in PHP. A unique `csrf_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 with the one in the session using `hash_equals()` for a secure comparison. If they don't match, the request is blocked, preventing unauthorized actions. Regenerating the token after use adds an extra layer of security.

Need help integrating this into your project?

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

Hire DigitalCodeLabs