🐘 PHP Intermediate

What is CSRF and how do you prevent it in PHP?

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.