Back to results for “Security”
PHP › Security

What is cross site request forgery, commonly called CSRF, and how do CSRF tokens help protect forms from this type of attack?

Intermediate

Answer

Cross site request forgery tricks a logged in user's browser into unknowingly submitting a request to an application they are authenticated with, such as changing their account settings or making a purchase, often by embedding a hidden form or link on a malicious page, and a CSRF token defends against this by including a unique, unpredictable value in every legitimate form that the server generated and remembers, then rejecting any submitted request that does not include that exact matching token, since an attacker's malicious page would have no way of knowing what that token's value actually is.
<input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token'] ?>">

// On submission
if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die('Invalid request');
}
Real-world example A banking application includes a unique CSRF token in its funds transfer form, ensuring that even if an attacker tricks a logged in user into visiting a malicious page that attempts to auto submit a transfer request, the request is rejected because it lacks the correct token value.

Common follow-ups: How often should a CSRF token be regenerated?;Do frameworks like Laravel handle CSRF protection automatically for you?