📖 Scenario: You are building a simple web form where users can submit their email to subscribe to a newsletter. To keep the form safe from CSRF (Cross-Site Request Forgery) attacks, you will add a CSRF token to the form and check it when the form is submitted.
🎯 Goal: Create a PHP script that generates a CSRF token, includes it in a form as a hidden input, and then validates the token when the form is submitted to protect against CSRF attacks.
📋 What You'll Learn
Create a PHP session to store the CSRF token
Generate a CSRF token and store it in the session
Add the CSRF token as a hidden input in the HTML form
Check the CSRF token on form submission to validate it
Display a success message if the token is valid, or an error message if invalid
💡 Why This Matters
🌍 Real World
CSRF tokens are used in web forms to prevent attackers from tricking users into submitting unwanted requests. This protects user data and actions on websites.
💼 Career
Understanding CSRF protection is essential for web developers and security engineers to build safe web applications and prevent common security vulnerabilities.
Progress0 / 4 steps
1
Start a PHP session and create a CSRF token
Write PHP code to start a session with session_start() and create a CSRF token string called csrf_token using bin2hex(random_bytes(32)). Store this token in the session variable $_SESSION['csrf_token'].
PHP
Hint
Use session_start() at the top. Then create $csrf_token with bin2hex(random_bytes(32)) and save it in $_SESSION['csrf_token'].
2
Add the CSRF token as a hidden input in the HTML form
Write HTML code for a form with method POST and action set to the same page. Inside the form, add an input field for email and a hidden input field named csrf_token with the value set to the PHP variable $csrf_token.
PHP
Hint
Use a hidden input with name="csrf_token" and set its value to .
3
Check the CSRF token on form submission
Add PHP code at the top to check if the form is submitted by verifying $_SERVER['REQUEST_METHOD'] === 'POST'. Then check if $_POST['csrf_token'] exists and matches $_SESSION['csrf_token']. Store the result in a variable called valid_token which is true if tokens match, otherwise false.
PHP
Hint
Check if the request method is POST. Then verify if $_POST['csrf_token'] exists and equals $_SESSION['csrf_token']. Set $valid_token accordingly.
4
Display success or error message based on CSRF token validation
Add PHP code after the form to print "Subscription successful!" if $valid_token is true. Otherwise, if the form was submitted but the token is invalid, print "Error: Invalid CSRF token.".
PHP
Hint
After the form, check if the form was submitted. If $valid_token is true, print success message. Otherwise, print error message.
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
Step 1: Understand CSRF attack basics
CSRF attacks trick a user into submitting unwanted actions on a trusted site.
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.
Final Answer:
To prevent unauthorized commands from being transmitted from a user the website trusts -> Option B
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
Step 1: Analyze token existence check
The code compares $_POST['csrf_token'] without verifying if it exists, risking undefined index error.
Step 2: Importance of isset()
Using isset() prevents errors by ensuring the token is present before comparison.
Final Answer:
Missing check if $_POST['csrf_token'] is set before comparing -> Option D
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
Step 1: Token generation and storage
Token must be generated before showing the form and stored in session to verify later.
Step 2: Embedding and validation
Embed the token in a hidden form field and check it against the session token on submission.
Final Answer:
Generate token on form display, store in session, embed in hidden input, then check token on form submission. -> Option A