Consider this PHP code snippet that checks a CSRF token from a form submission. What will it output if the submitted token matches the session token?
<?php session_start(); $_SESSION['csrf_token'] = 'abc123'; $submitted_token = 'abc123'; // Simulate form submission $_POST['csrf_token'] = $submitted_token; if (isset($_POST['csrf_token']) && $_POST['csrf_token'] === $_SESSION['csrf_token']) { echo 'Token valid'; } else { echo 'Token invalid'; }
Check if the submitted token matches the session token exactly.
The code sets the session token to 'abc123' and simulates a form submission with the same token. The condition passes, so it prints 'Token valid'.
What is the main reason web applications use CSRF tokens?
Think about how CSRF tokens protect against unauthorized form submissions.
CSRF tokens ensure that form submissions are made intentionally by the user and not by attackers forging requests.
Look at this PHP code snippet. It tries to check a CSRF token but always prints 'Token invalid'. What is the bug?
<?php session_start(); $_SESSION['csrf_token'] = 'token123'; if ($_POST['csrf_token'] === $_SESSION['csrf_token']) { echo 'Token valid'; } else { echo 'Token invalid'; } // Simulate form submission $_POST['csrf_token'] = 'token123';
Check the order of operations and when $_POST['csrf_token'] is set.
The code checks $_POST['csrf_token'] before it is set, so the condition fails. Setting $_POST['csrf_token'] after the check means the check always compares null to the token.
Which PHP code snippet will cause a syntax error when generating a CSRF token?
Look carefully for missing semicolons.
Option A is missing a semicolon at the end of the statement, causing a syntax error.
This PHP code stores multiple CSRF tokens for different forms in the session. How many tokens are stored in $_SESSION['csrf_tokens'] after running?
<?php session_start(); $_SESSION['csrf_tokens'] = []; for ($i = 1; $i <= 3; $i++) { $_SESSION['csrf_tokens']['form' . $i] = bin2hex(random_bytes(16)); } unset($_SESSION['csrf_tokens']['form2']);
Count how many tokens are added and then removed.
The loop adds 3 tokens with keys 'form1', 'form2', 'form3'. Then 'form2' is removed, leaving 2 tokens.