Home > Backend Development > PHP Tutorial > How to Securely Implement CSRF Tokens in PHP?

How to Securely Implement CSRF Tokens in PHP?

Patricia Arquette
Release: 2024-12-08 00:39:12
Original
328 people have browsed it

How to Securely Implement CSRF Tokens in PHP?

How to Implement CSRF Tokens in PHP: A Comprehensive Guide

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'];
Copy after login

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
    }
}
Copy after login

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']);
Copy after login
$calc = hash_hmac('sha256', '/my_form.php', $_SESSION['second_token']);
if (hash_equals($calc, $_POST['token'])) {
    // Continue...
}
Copy after login

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) { // ... }
    )
);
Copy after login
<input type="hidden" name="token" value="{{ form_token() }}" />
Copy after login

Or, for locked tokens:

<input type="hidden" name="token" value="{{ form_token('/my_form.php') }}" />
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template