Home >Backend Development >PHP Tutorial >How to Securely Implement CSRF Tokens in PHP?
Using Random Bytes for Strong Token Generation
In the context of CSRF token generation, using rand() and uniqid() poses security risks due to their predictability and limited entropy. Instead, opt for:
session_start(); if (empty($_SESSION['token'])) { $_SESSION['token'] = bin2hex(random_bytes(32)); } $token = $_SESSION['token'];
Verifying CSRF Tokens Securely
Avoid using direct equality checks (== or ===). Instead, employ hash_equals() for PHP 5.6 or paragonie/hash-compat for earlier versions:
if (!empty($_POST['token'])) { if (hash_equals($_SESSION['token'], $_POST['token'])) { // Proceed to form data processing } else { // Log and monitor these attempts } }
Enhancing Security with Per-Form Tokens
To restrict tokens to specific forms, use hash_hmac():
echo hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
$calc = hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']); if (hash_equals($calc, $_POST['token'])) { // Continue... }
Hybrid Approach for Simplicity
With Twig templating, you can simplify token generation using a custom Twig function:
$twigEnv->addFunction( new \Twig_SimpleFunction( 'form_token', function($lock_to = null) { // ... } ) );
<input type="hidden" name="token" value="{{ form_token() }}" />
Or, for locked tokens:
<input type="hidden" name="token" value="{{ form_token('/my_form.php') }}" />
Single-Use CSRF Tokens
If required, consider using a specialized library to manage single-use CSRF tokens, such as the Anti-CSRF Library by Paragon Initiative Enterprises.
The above is the detailed content of How to Securely Implement CSRF Tokens in PHP?. For more information, please follow other related articles on the PHP Chinese website!