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.
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