0
0
PHPprogramming~5 mins

CSRF attacks and token protection in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does CSRF stand for and what is it?
CSRF stands for Cross-Site Request Forgery. It is a type of attack where a malicious website tricks a user's browser into performing unwanted actions on a trusted site where the user is logged in.
Click to reveal answer
beginner
How does a CSRF token help protect against CSRF attacks?
A CSRF token is a unique, secret value generated by the server and included in forms. When the form is submitted, the server checks the token. If it matches, the request is valid. This prevents attackers from forging requests because they don't know the token.
Click to reveal answer
intermediate
Show a simple PHP code snippet to generate and store a CSRF token in a session.
<?php
session_start();
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>
Click to reveal answer
beginner
How do you include a CSRF token in an HTML form?
<form method="post" action="submit.php">
  <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
  <!-- other form fields -->
  <input type="submit" value="Submit">
</form>
Click to reveal answer
beginner
What is the server-side check for a CSRF token in PHP?
On form submission, the server compares the token sent in the form with the token stored in the session. If they match, the request is accepted; otherwise, it is rejected to prevent CSRF attacks.
Click to reveal answer
What is the main purpose of a CSRF token?
ATo speed up form submission
BTo verify the user is logged in
CTo encrypt user data
DTo prevent unauthorized form submissions from other sites
Where is a CSRF token usually stored on the server side?
AIn the user's session data
BIn a cookie accessible by JavaScript
CIn the URL query string
DIn a database table
Which PHP function is commonly used to generate a secure CSRF token?
Arand()
Bmd5()
Cbin2hex(random_bytes())
Duniqid()
What happens if the CSRF token in the form does not match the session token?
AThe request is rejected to prevent CSRF
BThe server redirects to the login page
CThe token is automatically updated
DThe request is accepted anyway
Why can't attackers easily guess the CSRF token?
ABecause it is stored in a cookie
BBecause it is a long, random string generated securely
CBecause it is encrypted with a password
DBecause it changes every second
Explain what a CSRF attack is and how a CSRF token helps prevent it.
Think about how a malicious site tricks a user and how a secret token stops that.
You got /3 concepts.
    Describe the steps to implement CSRF token protection in a PHP web form.
    Consider what happens before showing the form and after the form is submitted.
    You got /4 concepts.