carry0987/session-manager

为PHP提供灵活和安全的会话管理。此库为PHP的本地会话处理函数提供了一个面向对象的包装器,实现了SessionHandlerInterface,以便于与现有项目集成。它还提供了会话加密和数据库等附加功能。

1.0.10 2024-07-20 15:44 UTC

This package is auto-updated.

Last update: 2024-09-20 16:15:00 UTC


README

Packgist
现代PHP会话管理库

简介

SessionManager 是一个现代PHP会话管理库,它为PHP的本地会话处理函数提供了一个面向对象的包装器。它实现了 SessionHandlerInterface,允许与现有项目轻松集成。此外,它还提供了会话加密和数据库存储处理程序等额外功能,以支持可扩展的应用程序。

特性

  • 面向对象会话管理。
  • 防止会话固定攻击。
  • 自动处理会话过期。
  • CSRF令牌生成和验证机制。
  • 易于集成到现有项目或框架中。
  • 支持自定义会话名称和cookie参数。

安装

您可以通过Composer安装 SessionManager

composer require carry0987/session-manager

用法

以下是如何使用 SessionManager 的基本示例

require 'vendor/autoload.php';

use carry0987\SessionManager\SessionManager;

// Create a SessionManager instance, you may optionally supply a custom session name and cookie parameters
$sessionManager = new SessionManager('MY_SESSION_NAME', [
    'lifetime' => 3600,           // Cookie lifetime
    'secure' => true,             // Send only over HTTPS
    'httponly' => true,           // Accessible only through the HTTP protocol
    'samesite' => 'Strict'        // Strict same-site policy
]);

// Set a session variable
$sessionManager->set('username', 'user123');

// Retrieve a session variable
$username = $sessionManager->get('username');

// Destroy the session
$sessionManager->destroy();

// Renew the session
$sessionManager->renew('MY_SESSION_NAME');

安全特性

  • 会话固定攻击保护:SessionManager 定期重新生成会话ID。
  • 会话过期机制:会话在一段时间的不活跃后自动过期。
  • CSRF保护:生成和验证CSRF令牌。
  • 安全的cookie参数:默认情况下,cookie被标记为HttpOnly和Secure,以增强安全性。

API参考

以下是 SessionManager 提供的方法列表

  • set($key, $value): 设置会话变量。
  • get($key): 获取会话变量。
  • exists($key): 检查会话变量是否存在。
  • remove($key): 删除会话变量。
  • destroy(): 销毁会话。
  • 有关更详细的方法和用法说明,请参阅代码注释。

贡献

如果您有任何改进建议或功能请求,请提交问题或pull request。

许可

本项目采用MIT许可。有关更多信息,请参阅LICENSE文件。