0
0
PHPprogramming~5 mins

CSRF attacks and token protection in PHP

Choose your learning style9 modes available
Introduction

CSRF attacks trick a user into doing something unwanted on a website. Token protection stops these attacks by checking a secret code.

When you have forms that change user data, like updating a profile.
When users perform actions like making payments or changing passwords.
When you want to keep user accounts safe from unauthorized actions.
When your website uses sessions to remember users.
When you want to protect any request that changes data on the server.
Syntax
PHP
<?php
// Start session
session_start();

// Generate token
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Include token in form
?>
<form method="POST" action="process.php">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <!-- other form fields -->
    <input type="submit" value="Submit">
</form>

<?php
// On form submit, check token
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
        die('CSRF token validation failed');
    }
    // Process form safely
}
?>

Use session_start() to keep the token for each user.

Use hash_equals() to safely compare tokens and avoid timing attacks.

Examples
This example creates a shorter 16-byte token and includes it in a simple form.
PHP
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(16));
}
?>
<form method="POST">
    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">
    <input type="submit" value="Send">
</form>
This example shows how to check the token when the form is submitted.
PHP
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        echo 'Invalid CSRF token';
        exit;
    }
    echo 'Form processed safely';
}
?>
Sample Program

This program creates a CSRF token, adds it to a form, and checks it when the form is submitted. If the token is wrong or missing, it stops the process.

PHP
<?php
session_start();

// Generate CSRF token if not set
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

// Check if form submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die('CSRF token validation failed');
    }
    echo 'Form submitted successfully!';
    exit;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSRF Token Example</title>
</head>
<body>
    <h1>CSRF Token Protection Example</h1>
    <form method="POST">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required>
        <button type="submit">Submit</button>
    </form>
</body>
</html>
OutputSuccess
Important Notes

Always start the session before using CSRF tokens.

Never trust data from the user without checking the CSRF token.

Use random_bytes() for strong random tokens.

Summary

CSRF tokens protect users from unwanted actions by attackers.

Tokens are unique secrets stored in the session and sent with forms.

Always check the token before processing sensitive requests.