What is CSRF and how do you prevent it in PHP?
Why Interviewers Ask This
This question targets practical, hands-on experience with PHP. Interviewers want to see if you've worked with these concepts in real projects, not just read about them. Strong answers include concrete examples.
Answer
Cross-Site Request Forgery (CSRF) tricks an authenticated user's browser into making an unwanted request to a web application (like transferring money or deleting account) by exploiting the fact that the browser automatically sends cookies with requests. Prevention: generate a unique, unpredictable CSRF token per user session and include it in every form as a hidden field: <input type="hidden" name="_token" value="<?= $_SESSION["csrf_token"] ?>">. On form submission, verify the token matches: hash_equals($_SESSION["csrf_token"], $_POST["_token"]). Use hash_equals() (not ==) to prevent timing attacks. Also: set the SameSite cookie attribute (Strict or Lax) for additional protection. Laravel and Symfony do this automatically.
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex PHP answers easy to follow.
Previous
What is PHP's Autoloading?
Next
What is the difference between include_once and require_once?