Tuesday, March 18, 2014

Cross site request forgery (CSRF) Protection in PHP

Nowadays almost every website applies CSRF protection in their forms to make it more secure and safe. In this post i'll be first create a Class called Security and then we'll be making some methods to achieve the goal of making a Cross Site Request Forgery secure forms. Because of Cross site request forgery vulnerability an attacker can simply submit or process the form on behalf of the user without knowing of the users. This kinds of attacks are mainly done on E-commerce websites to place bogus orders.

Creating the Class:

Using the Class:

What we are doing here is first creating the class and then creating the 'Static' methods. The first thing what we have done is to get the token and then to inject it into our HTML using hidden input field. We have chosen hidden input type because we don't want the token (hash) to be displayed on our webpage.
We are also saving the token in the session so that we can verify it when user submits the form.

To verify the token we have build up a method called 'checkToken()' which firsts checks whether the token in set or not and then checks whether the token submitted by the user matches the token saved in our session. If it is then it first unset the session and then it returns a boolean value TRUE. If not then it returns FALSE.

Note:
Make sure you before using the Class you use session_start() function to start the session.