Home >Backend Development >PHP Tutorial >How to Securely Implement CSRF Token Protection in PHP Forms?
Introduction
Adding proper security fortifications to your website involves addressing potential vulnerabilities, including Cross-site Request Forgery (CSRF). This article delves into effectively adding a CSRF token using PHP.
Understanding the Issue
You've implemented CSRF token protection on your website, but the token's value is inconsistently present in the HTML forms. Specifically, the "contact us" and AJAX forms are exhibiting this issue.
Reviewing the Code
Let's scrutinize the code used for injecting the token:
PHP:
if (!isset($_SESSION)) { session_start(); $_SESSION['formStarted'] = true; } if (!isset($_SESSION['token'])) { $token = md5(uniqid(rand(), TRUE)); $_SESSION['token'] = $token; }
HTML:
<input type="hidden" name="token" value="<?php echo $token; ?>" />
Addressing the Weakness
Unfortunately, the current token generation method employs flawed techniques:
Implementing a Robust Token Generator
To safeguard your forms, utilize the following PHP code:
PHP 7:
session_start(); if (empty($_SESSION['token'])) { $_SESSION['token'] = bin2hex(random_bytes(32)); } $token = $_SESSION['token'];
PHP 5.3 (or with ext-mcrypt):
session_start(); if (empty($_SESSION['token'])) { if (function_exists('mcrypt_create_iv')) { $_SESSION['token'] = bin2hex(mcrypt_create_iv(32, MCRYPT_DEV_URANDOM)); } else { $_SESSION['token'] = bin2hex(openssl_random_pseudo_bytes(32)); } } $token = $_SESSION['token'];
Verifying the Token
Next, properly validate the CSRF token to prevent attempts at exploitation:
if (!empty($_POST['token'])) { if (hash_equals($_SESSION['token'], $_POST['token'])) { // Proceed to process the form data } else { // Log this as a warning and monitor such attempts } }
Additional Considerations
The above is the detailed content of How to Securely Implement CSRF Token Protection in PHP Forms?. For more information, please follow other related articles on the PHP Chinese website!