Advertisement
Advanced PHP, Form Handling & Validation

How does Cross-Site Request Forgery protection work for form submissions, and why is including a CSRF token in every form considered essential?

Short answer

Cross-Site Request Forgery, or CSRF, is an attack where a malicious website tricks a logged in user's browser into unknowingly submitting a request to another site where they are authenticated, and protecting against it involves including a unique, secret, randomly generated…

Save PHP mock interview
Advertisement
AModel answer
Cross-Site Request Forgery, or CSRF, is an attack where a malicious website tricks a logged in user's browser into unknowingly submitting a request to another site where they are authenticated, and protecting against it involves including a unique, secret, randomly generated token as a hidden field in every form, which the server verifies matches the token stored in the user's session before processing the submission, ensuring the request genuinely originated from your own legitimate form rather than a malicious third party site.
<form method="post">
  <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
</form>

if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    throw new SecurityException('Invalid CSRF token');
}
Real-world example
A banking application includes a CSRF token in its fund transfer form, preventing a malicious website from being able to trick a logged in user's browser into unknowingly submitting an unauthorized transfer request on their behalf.
Likely follow-ups
  • How does a CSRF token differ from a session identifier in terms of what it protects against?
  • How do modern frameworks automatically handle CSRF token generation and verification?
Related topics