maer/csrf
Composer 安装命令:
composer require maer/csrf
包简介
A small CSRF package for PHP
README 文档
README
Quickly generate and validate tokens to prevent Cross-Site Request Forgery (CSRF) attacks.
Important: This package only helps you with the CSRF tokens. To truly be safe from CSRF, you also need to protect yourself against Cross-site scripting (XSS) as well.
Install
Git clone or use composer to download the package with the following command:
composer require maer/csrf 1.*
Usage
Include composers autoloader or include the files in the src/ folder manually. (start with CsrfInterface.php-file)
Create a new instance
$csrf = new Maer\Security\Csrf\Csrf();
Important: You can create a new instance when ever in your application, but before you make any calls to it, you need to start the session yourself. This package does not make any assumptions on how you manage your sessions (you might use: session_start() or you might use Symfonys Session package etc...)
Approach 1: Manually add the hidden field
<form method="post" action="...">
<input type="hidden" name="csrftoken" value="<?= $csrf->getToken() ?>" />
...
</form>
Approach 2: Generate the hidden field
<form method="post" action="...">
<?= $csrf->getTokenField() ?>
...
</form>
Validate
When receiving the post:
if ($csrf->validateToken($_POST['csrftoken'])) {
echo "Yay! It's a valid token!";
} else {
echo "Nope. That token isn't valid!";
}
Extra goodies
Named tokens
All methods takes an optional $name argument. This gives you the option of having multiple tokens through out your application. For example:
$csrf->getToken();
$csrf->getToken('login-form');
$csrf->getToken('something-else');
The above will generate three different tokens and the same goes for the getTokenField()-method.
To validate named tokens, set the name as the second argument to the validateToken()-method:
$csrf->validateToken($_POST['csrftoken'], 'login-form');
Regenerate tokens
If you want to invalidate an existing token, use the regenerateToken()-method. This method also returns the new token, so if you want to have different tokens every time a form is loaded, you can use this method instead of generateToken()
$token = $csrf->regenerateToken();
// or for a named token
$token = $csrf->regenerateToken('login-form');
Reset/remove all tokens
This will remove all tokens, named or not.
$csrf->resetAll();
Note
If you have any questions, suggestions or issues, let me know!
Happy coding!
maer/csrf 适用场景与选型建议
maer/csrf 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.08k 次下载、GitHub Stars 达 5, 最近一次更新时间为 2015 年 10 月 16 日, 在 PHP 生态内属于活跃度较高的组件。
我们在过去多个企业项目中使用过 maer/csrf 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 maer/csrf 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
统计信息
- 总下载量: 3.08k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 6
- 点击次数: 18
- 依赖项目数: 2
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2015-10-16