yggdevsec / csrf
CSRF protection library
1.0
2025-06-21 15:26 UTC
Requires
- php: ^8.3 || ^8.4
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.75
- phpstan/phpstan: ^2.1
- phpunit/phpunit: ^10.5
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! ☕️
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