Apply CSRF in the PHP application to prevent CSRF attacks

Apply CSRF in the php application to prevent CSRF attacks

Nowadays, it is very important to implement secure an application from CSRF attacks. In this article, we will apply CSRF in the PHP application to prevent CSRF attacks.

What is CSRF?

CSRF stands for Cross-site request forgery. It is a type of malicious exploit of a website where unauthorized commands are submitted from a user that the web application trusts. A CSRF token is a unique, unpredictable value that is generated by the server-side application and transmitted to the user in such a way that it is included in the HTTP request made by the user.

How to prevent CSRF attacks?

The CSRF attacks can be prevented by generating a security token at the server-side. This security token will then be verified when a form is submitted (or when a request is made). There is a term called “origin policy”, and it is important to keep the same-origin policy. If the origin policy is the same the attacker can’t even read the response that contains the token.

Let’s apply CSRF in the PHP application to prevent CSRF attacks

There are many ways to implement CSRF in the PHP application, so let’s try an implementation using PHP session functions.

When using sessions we first have to start it using the code below:


Now, in the login process when the user credentials are authenticated you need to generate a unique, secure string and store it in the session variable.

Add the following code to create a unique random string:

  $random_token = bin2hex(random_bytes(32));
  $_SESSION['csrfToken'] = $random_token;

We have the unique string generated on the server-side which a hacker can not get while generating an attacking attempt. The next step is to pass this string with the form as a hidden field, the markup is:

<input type="hidden" name="csrfToken" value="<?php echo $_SESSION['csrfToken']; ?>" />

Now, we have to verify the generated string on the form process page to make sure the incoming request is from the “same-origin”. The PHP code is:

  if (!hash_equals($_SESSION['csrfToken'], $_POST['csrfToken'])) {
    echo 'Error! CSRF attack detected';
    // redirection to access denied page or any other logic

If the token is not validated the form will not process, so in this way, a hacker may send the request but the server will discard it.

So, the application now prevents CSRF attacks.

Related Posts