定制 yggdevsec/csrf 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

yggdevsec/csrf

最新稳定版本:1.0

Composer 安装命令:

composer require yggdevsec/csrf

包简介

CSRF protection library

README 文档

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

统计信息

  • 总下载量: 3
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-06-21