How To Prevent Cross Site Request Forgery (CSRF) Attacks in PHP

A cross site request forgery attack can be prevented by including a random token with each request or using random names for each form field.A cross site request forgery (CSRF) attack exploits a web application vulnerability where the victim unintentionally runs a script in their browser that takes advantage of their logged in session to a particular site.CSRF attacks can be performed over the internet.

Step 1: Understand the two ways to prevent CSRF attacks.

Each request has a random token included.Each session a unique string is generated.We include the token in every form as a hidden input after generating it.The system compares the token with the one stored in the user's session variable to see if the form is valid.Without knowing the token value, an attacker won't be able to generate a request.Each form field has a random name.A session variable holds the random name for each field.The system creates a new random value after the form has been submitted.An attacker would have to guess the random form names.For example a request that used to look like this.

Step 2: Csrf.class.php should be created.

The functions in this file will be used to prevent CSRF attacks.class csrf

Step 3: The file needs to be saved.

The code in Parts 2 and 3 will be added to this file.

Step 4: The get_token_id function needs to be created.

The function retrieves the token ID from a user's session and if one has not already been created a random token is generated.public function get_token_id

Step 5: The get_token function should be created.

If one has not been generated, the function retrieves the token value.If(isset($_SESSION['token_value']) is returned, else $token is used.

Step 6: The check_valid function needs to be created.

The function determines if the token ID and token value are valid.The values of the GET or POST request are checked against the values in the user'sSESSION variable.If(isset($$Method[$this]) is true, public function check_valid.

Step 7: The form_names function needs to be created.

Random names are generated for the form fields.If($regenerate]) is true, foreach ($names as $n) unset($_SESSION[$n]);$_SESSION[$n] : random(10), $s, and $values, return $ values.

Step 8: The random function needs to be created.

The Linux random file is used to generate a random string.If function_exists('openssl_random_pseudo_bytes'), it's a private function.

Step 9: The class csrf brackets should be closed.

.

Step 10: The class.html file needs to be closed.

Step 11: The CSRF Class file can be added to a POST Form.

Adding the CSRF Class file to a POST form is shown in the code pictured here.?php session start; include 'csrf.class.php'Get the Form Variables if($csrf->check_valid)('post'))Form Function Goes Here // Regenerate a new random value for the form.$form_names is the name of the form, it is true.