Give us a second

Cross Site Request Forgery

Secure PHP Routing against CSRF

Cross Site Request Forgery (CSRF)

Cross Site Request Forgery (CSRF) works with sessions in PHP. Therefore, you must include session_start() at the beggining of the file that will have the form with the token in it.

To secure a form agains CSRF create the needed input fields in the form and make sure that you call the set_csrf() function. This function will create an input field with the required CSRF token in it.

<form action="/route" method="POST">
  <?php set_csrf() ?>
  <input type="text" value="">

To check if the form has not been CSRForget, use the function is_csrf_valid() by adding it to the route that will receive the POSTed form:

// This line in routes.php
post('/route', 'create_user.php');

In the create_user.php file, you must check if the CSRF is forged or not by using the following function.


if( ! is_csrf_valid() ){
  // The form is forged
  // Code here
// Code here form is legit

Example of a form with CSRF

The following form contains a CSRF token. You will not be able to see the input field that has the mentioned token since it is hidden by default. Yet, you can inspect the form and you will see it there.

What is Cross Site Request Forgery (CSRF)?

To keep it simple, CSRF is a technique in which a hacker (human or bot) tries to send a request to the server in behalf of the user who is logged into the system.

If CSRF is successful, the server will think that the verified and logged user is sending the request. In reality, the hacker is doing it.

How does CSRF access session/cookies?

Once a user logs into the system, a session/cookie is set in the browser. This cookie will be sent to the server anytime a request is triggered. The request can be created by a hiperlink, form submission, ajax/fetch, or any other method that will connect the client to the server.

Those types of request will be exploded by the hacker by triggering them and making the server believe that the user did it. Since the request will include the cookie, the server will think this is legit and will react upon it as if it were the user who started it.

How PHP Router protects against CSRF?

Since the cookie can be accessed by the hacker, this library secures againt it by adding a random generated token to a form. This token cannot be reached by the hacker. The same token is in the client and also in the server.

Upon any request, the cookie will be passed, but the token injected in the form will not. Therefore the library checks if the token in the client matches the token in the server. If there is a match, then the request is legit and no Cross Site Request Forgery will take effect.

What if the request is ajax/fetch?

Inject the token in the form as you will normally do it.

When the request is triggered via ajax/fetch, make sure that the token in the form is also passed to the server.