How do I protect against CSRF in PHP?

Cross-Site Request Forgery (CSRF) is a type of attack that tricks the victim into submitting a request that they did not intend to make. In PHP, it is crucial to implement strategies to protect your application against CSRF attacks. Here are some effective methods:

1. Use CSRF Tokens

Generate a unique token for each session and include it in forms. Validate the token during form submissions.

2. Validate Referrer Headers

Check the HTTP referrer header to ensure that the request is coming from your site.

3. SameSite Cookies

Utilize the SameSite attribute in cookies to prevent them from being sent with cross-origin requests.

4. Implement Anti-CSRF Libraries

Consider using established libraries that help manage CSRF protection effectively.

Example Implementation

<?php session_start(); // Generate a CSRF token if(empty($_SESSION['csrf_token'])) { $_SESSION['csrf_token'] = bin2hex(random_bytes(32)); } // Validate CSRF token on form submission if($_SERVER['REQUEST_METHOD'] === 'POST') { if(!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { die('CSRF token validation failed'); } // Process the form } ?> <form method="POST"> <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']; ?>"> <!-- other form fields --> <input type="submit" value="Submit"> </form>

CSRF protection PHP CSRF token Cross-Site Request Forgery secure PHP applications anti-CSRF techniques