Home > Dev > PHP Security > CSRF Protection

CSRF Protection

This code generates and validates CSRF tokens to protect against cross-site request forgery (CSRF) attacks.

session_start();

function generate_csrf_token() {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

function validate_csrf_token($token) {
    return hash_equals($_SESSION['csrf_token'], $token);
}

// Usage example in form
$csrf_token = generate_csrf_token();
echo '<input type="hidden" name="csrf_token" value="'.$csrf_token.'">';

// Validate token on form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!validate_csrf_token($_POST['csrf_token'])) {
        die('Invalid CSRF token');
    }
}
Back