0
0
PHPprogramming~10 mins

CSRF attacks and token protection in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - CSRF attacks and token protection
User visits form page
Server generates CSRF token
Token stored in session and form
User submits form with token
Server checks token validity
Process form
The server creates a unique token for the user session and includes it in the form. When the form is submitted, the server checks the token to confirm the request is genuine.
Execution Sample
PHP
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    die('CSRF token invalid');
  }
  echo 'Form processed';
}
?>
This PHP code generates a CSRF token, stores it in the session, and checks it on form submission to protect against CSRF attacks.
Execution Table
StepActionToken in SessionToken in POSTCheck ResultOutput
1Start session, check tokennonenoneToken generatednone
2User loads formabc123token...nonenoneForm with token sent
3User submits formabc123token...abc123token...Tokens matchForm processed
4User submits form with wrong tokenabc123token...wrongtokenTokens do not matchCSRF token invalid
5Endabc123token...variesProcess endsnone
💡 Execution stops when token check fails or form is processed successfully.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4Final
$_SESSION['csrf_token']noneabc123token...abc123token...abc123token...abc123token...abc123token...
$_POST['csrf_token']nonenonenoneabc123token...wrongtokenvaries
Key Moments - 3 Insights
Why do we store the CSRF token in the session?
The session stores the token securely on the server side so it can be compared with the token submitted by the user to verify authenticity, as shown in step 3 of the execution_table.
What happens if the token in the POST data does not match the session token?
The server rejects the request and stops processing, outputting 'CSRF token invalid' as shown in step 4 of the execution_table.
Why do we generate a new token only if none exists?
To keep the same token for the user's session until it expires or changes, ensuring consistency between form and session tokens, as seen in step 1.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the output when the tokens match at step 3?
ACSRF token invalid
BForm with token sent
CForm processed
DToken generated
💡 Hint
Check the 'Output' column at step 3 in the execution_table.
At which step does the server generate the CSRF token?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Action' and 'Check Result' columns in the execution_table for token generation.
If the token in the POST data is missing, what will happen according to the code?
ACSRF token invalid error
BToken is generated again
CForm processed normally
DSession token is deleted
💡 Hint
Refer to the token check in the code and the 'Check Result' column in the execution_table for invalid tokens.
Concept Snapshot
CSRF protection uses a unique token stored in the user session and included in forms.
On form submission, the server compares the submitted token with the session token.
If tokens match, the request is valid; otherwise, it is rejected.
Tokens prevent attackers from forging requests on behalf of users.
Generate tokens once per session and verify on every POST request.
Full Transcript
This visual trace shows how CSRF token protection works in PHP. First, the server starts a session and generates a unique token if none exists. This token is saved in the session and included in the HTML form sent to the user. When the user submits the form, the server compares the token sent in the POST data with the session token. If they match, the form is processed safely. If not, the server rejects the request to prevent CSRF attacks. The execution table tracks these steps, showing token values and outcomes. Key moments clarify why the token is stored in the session and what happens on mismatch. The quiz tests understanding of token generation, matching, and failure cases.