timefrontiers/php-session
Composer 安装命令:
composer require timefrontiers/php-session
包简介
Modern PHP session manager with authentication state, access control, and CSRF protection
README 文档
README
Modern PHP session manager with authentication state, access control, CSRF protection, and geolocation.
Installation
composer require timefrontiers/php-session
Features
- Secure session handling with HTTPOnly, SameSite cookies
- User authentication state management
- Access rank/group based authorization
- CSRF token generation and validation
- Flash messages
- IP geolocation integration
- PSR-3 logger support
Quick Start
use TimeFrontiers\Session; use TimeFrontiers\AccessRank; // Start session $session = new Session(); // Check if logged in if (!$session->isLoggedIn()) { // Show login form } // Access user info echo $session->id(); // e.g. 1 echo $session->name; // uniqueid e.g. "01234567890" echo $session->access_rank(); // 4 (MODERATOR) echo $session->access_group(); // AccessGroup::MODERATOR // Full user object $user = $session->user(); echo $user->surname; // Geolocation $loc = $session->location(); echo $loc?->country;
Authentication
Login
// User object from your database — must have 'id' and 'uniqueid' $user = (object)[ 'id' => 123, 'uniqueid' => '01234567890', 'name' => 'John', 'surname' => 'Doe', 'access_group' => AccessGroup::MODERATOR, 'access_rank' => AccessRank::MODERATOR, ]; // Login with 30-minute session (default) $session->login($user); // Custom session lifetime (2 hours) $session->login($user, session_lifetime: 7200);
Note: "Remember me" / persistent login requires storing a token in your database and is intentionally left to the application layer.
Logout
$session->logout();
Check Authentication
if ($session->isLoggedIn()) { $userId = $session->getUserId(); // or $session->id() $name = $session->name; // uniqueid of logged-in user $user = $session->user(); // full user object }
Access Control
use TimeFrontiers\AccessRank; // Check rank if ($session->hasRank(AccessRank::MODERATOR)) { // Can moderate } // Check group if ($session->inGroup(AccessGroup::ADMIN)) { // Is admin } // Convenience methods if ($session->isStaff()) { } // MODERATOR or higher if ($session->isTechnical()) { } // DEVELOPER or higher if ($session->isAdmin()) { } // ADMIN or higher // Via getters if ($session->access_rank() >= AccessRank::DEVELOPER->value) { // Show debug info }
CSRF Protection
Generate Token
// In your form $token = $session->generateCSRFToken('contact_form');
<form method="post"> <input type="hidden" name="_csrf_token" value="<?= $token ?>"> <!-- form fields --> </form>
Or use the helper:
echo $session->csrfField('contact_form'); // Outputs: <input type="hidden" name="_csrf_token" value="...">
Validate Token
if (!$session->validateCSRFToken('contact_form', $_POST['_csrf_token'])) { die('Invalid CSRF token'); }
Tokens are single-use and automatically expire (default: 1 hour). Expired tokens from other forms are pruned automatically on each generateCSRFToken() call.
User Object Storage
set(), get(), has(), and remove() operate on the authenticated user object and are persisted to the session. Use these to attach extra data to the user mid-session.
// Store data on the user object $session->set('theme', 'dark'); // Retrieve $theme = $session->get('theme', 'light'); // Default: 'light' // Check existence if ($session->has('theme')) { } // Remove $session->remove('theme'); // Get all user object properties as array $all = $session->all();
Flash Messages
Flash messages persist for one request only.
// Set flash message $session->flash('success', 'Profile updated!'); // Redirect... // Get and remove flash message if ($session->hasFlash('success')) { echo $session->getFlash('success'); }
Session Expiry
// Get expiration timestamp $expires = $session->getExpiry(); // Check if expired if ($session->isExpired()) { // Re-authenticate } // Extend session by 30 minutes $session->extendExpiry(1800);
Geolocation
Requires timefrontiers/php-location:
// Refresh location from IP $session->refreshLocation(); // Access location data $loc = $session->location(); if ($loc) { echo $loc->country; // "United States" echo $loc->country_code; // "US" echo $loc->city; // "San Francisco" echo $loc->currency_code; // "USD" }
Logging
Pass a PSR-3 logger for session events:
use Monolog\Logger; use Monolog\Handler\StreamHandler; $logger = new Logger('session'); $logger->pushHandler(new StreamHandler('session.log')); $session = new Session($logger);
Error Handling
Session uses static error collection for compatibility with InstanceError:
use TimeFrontiers\InstanceError; $session->login($invalidUser); if ($session->hasErrors()) { $extractor = new InstanceError($session); $errors = $extractor->get('login'); foreach ($errors as $err) { echo $err[2]; // Error message } } // Clear errors Session::clearErrors();
Security Features
- Session ID regeneration on login (prevents fixation)
- Secure cookies (HTTPOnly, SameSite=Lax)
- HTTPS-only cookies when available
- Timing-safe CSRF token comparison (
hash_equals) - Single-use CSRF tokens with automatic expiry pruning
- No session ID regeneration on every request (prevents concurrency issues)
Dependencies
psr/log- For PSR-3 logger interfacetimefrontiers/php-core- For AccessRank and AccessGroup enumstimefrontiers/php-instance-error- For error extraction
Optional Dependencies
timefrontiers/php-location- For IP geolocation
License
MIT
timefrontiers/php-session 适用场景与选型建议
timefrontiers/php-session 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 26 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 04 月 14 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「php」 「security」 「Authentication」 「manager」 「session」 「csrf」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 timefrontiers/php-session 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 timefrontiers/php-session 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 timefrontiers/php-session 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Automatically logs-in users if they are already authenticated by a remote source. (e.g. environment variable REMOTE_USER)
GraphQL authentication for your headless Craft CMS applications.
Provide a way to secure accesses to all routes of an symfony application.
Laravel middleware to restrict a site or specific routes using HTTP basic authentication
It's a barebone security class written on PHP
Email Toolkit Plugin for CakePHP
统计信息
- 总下载量: 26
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 44
- 依赖项目数: 0
- 推荐数: 2
其他信息
- 授权协议: MIT
- 更新时间: 2026-04-14