mrclay / userland-session

提供基于HTTP cookie的会话,纯PHP实现,允许与现有本地会话并发使用。

3.0.0 2014-05-25 01:38 UTC

This package is auto-updated.

Last update: 2024-09-07 05:02:11 UTC


README

https://travis-ci.org/mrclay/UserlandSession.png?branch=master

UserlandSession是一个基于HTTP cookie的会话组件,用纯PHP实现,允许它与现有本地会话并发使用,且完全独立。这使得它非常适合在不同不兼容会话的多个PHP应用程序之间桥接会话状态。

  • 松散耦合的组件,不引入全局状态(除了头部信息)
  • 使用PHP的SessionHandlerInterface,因此可以重用现有的第三方处理程序
  • 会话数据只能通过对象访问,而不是全局访问
// create a files-based session, directory sniffed from session.save_path
$session = \UserlandSession\SessionBuilder::instance()->build();
$session->start();

// use public $session->data array property...
$session->data['foo'] = 'bar';

// ...or use set/get()
$session->set('foo', 'bar');

$session->writeClose(); // ...or let destructor do this

处理程序

保存处理程序接口是PHP的SessionHandlerInterface,包括FileHandler和PdoHandler处理程序。

请随意使用自己的保存处理程序类,或者使用这些作为本地会话的处理程序!

创建会话

轻松获取基于文件的会话的方法

// from script (save path sniffed from session.save_path)
$session = (require 'path/to/UserlandSession/scripts/get_file_session.php');

// using builder (here we set the session name to MYSESS)
$session = SessionBuilder::instance()
    ->setSavePath('/tmp')
    ->setName('MYSESS')
    ->build();

文件存储选项

// turn off file locking
$session = SessionBuilder::instance()
    ->setFileLocking(false)
    ->build();

使用PDO

// pre-existing PDO connection
$session = SessionBuilder::instance()
    ->setPdo($myConnection)
    ->setTable('userland_sessions')
    ->build();

// or if you want it to connect for you when needed:
$session = SessionBuilder::instance()
    ->setDbCredentials(array(
        'dsn' => 'mysql:host=localhost;dbname=ulsess;charset=UTF8',
        'username' => 'fred',
        'password' => 'password1',
    ))
    ->setTable('userland_sessions')
    ->build();

附加功能

您可以在不启动会话的情况下检查与客户端cookie匹配的数据

if ($session->sessionLikelyExists()) {
    $session->start();
    // use session
} else {
    // don't start if we don't need to
}

更简单的cookie删除

$session->removeCookie();

// or specify true when destroying the session
$session->destroy(true);

许可证

MIT。见LICENSE。