PHP CSRF Protection.

This is a short tutorial on how to guard against CSRF in PHP. Cross-site Request Forgery (CSRF) is a type of attack whereby the user is tricked into performing an action that they didn’t intend on carrying out. This could be as simple as directing the user to a logout URL or something as serious tricking them into deleting a resource.

Example CSRF Attack.

An example of a CSRF attack:

If an attacker manages to trick a user into viewing the above “image”, then the resulting HTTP request from the user’s browser could result in the deletion of an important resource. The browser will attempt to load the URL; resulting in a HTTP request being created by the user.

To guard against these kind of attacks, we can give the user a randomly generated CSRF token as soon as he or she logs in. We can then add this CSRF token to our HTML forms and to our query string parameters.

Generating a secure token with PHP’s openssl_random_pseudo_bytes function is actually pretty straight-forward:

We can then add that to our HTML forms (with a hidden field) like so:

Or we can include the token as a query string parameter:

Then, when the user is attempting to carry out an important action, we can validate the CSRF token by comparing the received token against the token that has been stored in the user’s session:

As you can see, protecting against CSRF in PHP isn’t difficult. It just takes a little bit of added code!

Facebook Comments