How to implement CSRF protection in PHP?

Member

by aubrey , in category: PHP Security , a year ago

How to implement CSRF protection in PHP?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jasen , a year ago

@aubrey 

To implement CSRF (Cross-Site Request Forgery) protection in PHP, you can follow the below steps:

  1. Generate a random token: You need to generate a unique token for each session that a user initiates on your website. This token should be long and complex enough to be difficult to guess.
1
2
3
4
<?php
  session_start();
  $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
?>


  1. Add the token to the form: The token needs to be added to every form on your website. You can add it as a hidden field in the form.
1
<input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">


  1. Verify the token: When a form is submitted, you need to verify that the token in the form matches the token in the session. If they do not match, it means the request was not initiated by the user and should be rejected.
1
2
3
4
5
6
<?php
  session_start();
  if ($_POST['csrf_token'] !== $_SESSION['csrf_token']) {
    die("Invalid CSRF token");
  }
?>


  1. Use HTTPS: It is recommended to use HTTPS to encrypt the communication between the client and the server. This prevents an attacker from intercepting the token and using it for a malicious request.


By implementing these steps, you can add an extra layer of security to your web application and protect against CSRF attacks.