Bird
Raised Fist0
PHPprogramming~5 mins

CSRF attacks and token protection in PHP

Choose your learning style10 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.

Practice

(1/5)
1. What is the main purpose of a CSRF token in a PHP web application?
easy
A. To speed up the loading time of the website
B. To prevent unauthorized commands from being transmitted from a user the website trusts
C. To encrypt user passwords before storing them
D. To validate user input format on forms

Solution

  1. Step 1: Understand CSRF attack basics

    CSRF attacks trick a user into submitting unwanted actions on a trusted site.
  2. Step 2: Role of CSRF token

    A CSRF token is a unique value that verifies the request is from the legitimate user, preventing unauthorized commands.
  3. Final Answer:

    To prevent unauthorized commands from being transmitted from a user the website trusts -> Option B
  4. Quick Check:

    CSRF token purpose = prevent unauthorized commands [OK]
Hint: CSRF tokens stop fake requests from trusted users [OK]
Common Mistakes:
  • Confusing CSRF tokens with password encryption
  • Thinking CSRF tokens speed up websites
  • Believing CSRF tokens validate input format
2. Which PHP function is commonly used to generate a CSRF token?
easy
A. random_bytes()
B. md5()
C. htmlspecialchars()
D. strtoupper()

Solution

  1. Step 1: Identify secure token generation

    CSRF tokens must be random and hard to guess, so secure random functions are used.
  2. Step 2: Choose the correct function

    random_bytes() generates cryptographically secure random bytes, suitable for tokens.
  3. Final Answer:

    random_bytes() -> Option A
  4. Quick Check:

    Secure token generation = random_bytes() [OK]
Hint: Use random_bytes() for secure token generation [OK]
Common Mistakes:
  • Using md5() which is not secure for tokens
  • Confusing htmlspecialchars() with token generation
  • Using strtoupper() which only changes case
3. What will the following PHP code output if the CSRF token in session matches the token sent in POST?
$_SESSION['csrf_token'] = 'abc123';
if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) {
    echo 'Valid request';
} else {
    echo 'Invalid request';
}
medium
A. No output
B. Invalid request
C. Valid request
D. Undefined index error

Solution

  1. Step 1: Check token comparison logic

    The code compares the POST token with the session token for equality.
  2. Step 2: When tokens match

    If tokens match, it echoes 'Valid request'. If not, 'Invalid request'.
  3. Final Answer:

    Valid request -> Option C
  4. Quick Check:

    Matching tokens = Valid request [OK]
Hint: Matching tokens means valid request output [OK]
Common Mistakes:
  • Assuming error if POST token is set correctly
  • Ignoring isset() check causing errors
  • Thinking output is empty when tokens match
4. Identify the error in this PHP CSRF token validation snippet:
session_start();
if ($_POST['csrf_token'] == $_SESSION['csrf_token']) {
    echo 'Token valid';
} else {
    echo 'Token invalid';
}
medium
A. session_start() should be called after token check
B. Using == instead of === causes token mismatch
C. Tokens should be compared with strtolower()
D. Missing check if $_POST['csrf_token'] is set before comparing

Solution

  1. Step 1: Analyze token existence check

    The code compares $_POST['csrf_token'] without verifying if it exists, risking undefined index error.
  2. Step 2: Importance of isset()

    Using isset() prevents errors by ensuring the token is present before comparison.
  3. Final Answer:

    Missing check if $_POST['csrf_token'] is set before comparing -> Option D
  4. Quick Check:

    Check token existence before compare = Missing isset() [OK]
Hint: Always check if POST token exists before comparing [OK]
Common Mistakes:
  • Ignoring isset() causing runtime errors
  • Thinking == vs === affects token validation here
  • Calling session_start() after token check
5. You want to protect a PHP form from CSRF attacks. Which sequence correctly implements token generation, embedding, and validation? A) Generate token on form display, store in session, embed in hidden input, then check token on form submission. B) Generate token on form submission, embed in hidden input, then store in session. C) Store token in session after form submission, then generate token and embed in form. D) Embed a static token in the form and check it on submission without session.
hard
A. Generate token on form display, store in session, embed in hidden input, then check token on form submission.
B. Generate token on form submission, embed in hidden input, then store in session.
C. Store token in session after form submission, then generate token and embed in form.
D. Embed a static token in the form and check it on submission without session.

Solution

  1. Step 1: Token generation and storage

    Token must be generated before showing the form and stored in session to verify later.
  2. Step 2: Embedding and validation

    Embed the token in a hidden form field and check it against the session token on submission.
  3. Final Answer:

    Generate token on form display, store in session, embed in hidden input, then check token on form submission. -> Option A
  4. Quick Check:

    Token lifecycle = generate, store, embed, validate [OK]
Hint: Generate and store token before form, validate after submission [OK]
Common Mistakes:
  • Generating token after form submission
  • Not storing token in session
  • Using static tokens without session storage
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard