CSRF protection library

Installs: 3

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Forks: 0

pkg:composer/yggdevsec/csrf

1.0 2025-06-21 15:26 UTC

This package is auto-updated.

Last update: 2025-12-22 18:19:04 UTC


README

A simple, secure, and testable CSRF protection library for PHP 8.3+.

Support

If you like this project, feel free to support me with a coffee! ☕️

Buy Me a Coffee

Features

  • ✅ Stateless CSRF token generation using random_bytes
  • ✅ Multiple token keys (e.g. per-form support)
  • ✅ PSR-4 autoloading
  • ✅ Facade for ease-of-use
  • ✅ Testable with interface abstraction

Quality Assurance

  • ✅ Code analyzed with PHPStan at level 9
  • ✅ Code formatted and cleaned with PHP-CS-Fixer
  • ✅ Comprehensive unit tests

Installation

composer require yggdevsec/csrf

Basic Usage

Generating a Token in a Form

<?php

use YggDevSec\Security\Csrf\CsrfFacade;
?>

<form method="POST" action="/login.php">
    <?= CsrfFacade::getTokenField('login') ?>
    
    <input type="text" name="username" placeholder="Username">
    <input type="password" name="password" placeholder="Password">
    <button type="submit">Log in</button>
</form>

Validating the Token Server-Side

<?php

use YggDevSec\Security\Csrf\CsrfFacade;

$token = $_POST['_csrf_token_login'] ?? null;

if (!CsrfFacade::isValid('login', $token)) {
    http_response_code(403);
    die('Invalid CSRF token.');
}

// Proceed with request handling...

Testing

To run the test suite:

./vendor/bin/phpunit --testdox tests

To run static analysis:

./vendor/bin/phpstan analyse --level=max src

To check and fix code style:

./vendor/bin/php-cs-fixer fix --dry-run --diff

🔒 Security Considerations

  • Tokens are generated using random_bytes() for strong entropy
  • Tokens are stored in $_SESSION, so make sure session handling is active
  • Supports multiple named tokens, ideal for handling different forms

Folder Structure

src/
├── CsrfFacade.php
├── CsrfInterface.php
├── CsrfError.php
└── Csrf.php

tests/
└── CsrfTest.php

License

This project is licensed under the MIT License.

YggDevSec
Security-focused PHP libraries
https://gitlab.com/yggdevsec