Preventing Cross Site Request Forgeries(CSRF) in Core PHP

In this blog post, you will learn how to prevent the cross site request forgeries in the PHP.



Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF. Here the hacker submits the forms internally by using automation tools to spam the websites or applications, So to get rid of this type of unauthorized submission by attackers we have to use some rules in PHP. Here you need to send the token keys by users which are generated randomly and saved in the session variable.

Preventing Cross Site Request Forgeries(CSRF) in Core PHP

How to Prevent CSRF in Core PHP

 



Step-1: Generate Random Token by using mt_rand() and Encrypt it by using md5()

 

 

Step-2: Send this token to Server page by hidden input field inside the form.

 



Step-3: Validate it using PHP

 

Now we can combine all the code



 

 

So this code can prevent hackers to submit forms internally, he needs to know the token code saved in session before submitting the forms.

 



Tags: ,