PHP code example of kode / session
1. Go to this page and download the library: Download kode/session library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
kode / session example snippets
use Kode\Session\SessionManager;
$manager = new SessionManager([
'default' => 'file',
'drivers' => [
'file' => [
'path' => '/tmp/sessions',
'prefix' => 'sess_',
],
],
]);
$session = $manager->make(bin2hex(random_bytes(16)));
$session->start();
$session->set('user_id', 123);
$session->set('username', 'kode');
echo $session->get('username');
$session->close();
use Kode\Session\SessionManager;
use Kode\Session\Middleware\SessionMiddleware;
$manager = new SessionManager([...]);
$middleware = new SessionMiddleware($manager, [
'name' => 'KODE_SESSION',
'lifetime' => 3600,
'path' => '/',
'secure' => false,
'http_only' => true,
]);
use Kode\Session\Driver\FileDriver;
$driver = new FileDriver([
'path' => '/tmp/sessions',
'prefix' => 'kode_sess_',
'lock_path' => '/tmp/sessions/locks',
]);
use Kode\Session\Driver\RedisDriver;
$driver = new RedisDriver([
'prefix' => 'kode_sess_',
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
'password' => null,
'database' => 0,
],
]);
use Kode\Session\Driver\CookieDriver;
$driver = new CookieDriver([
'name' => 'kode_session',
'lifetime' => 3600,
'path' => '/',
'secure' => false,
'http_only' => true,
'samesite' => 'Lax',
]);
use Kode\Session\Driver\ArrayDriver;
$driver = new ArrayDriver(); // 可选传入 ['gc_probability' => 100] 强制每次 GC
use Kode\Session\Driver\DatabaseDriver;
$driver = new DatabaseDriver([
'dsn' => 'mysql:host=127.0.0.1;dbname=kode;charset=utf8mb4',
'username' => 'kode',
'password' => 'secret',
'table' => 'kode_sessions', // 会话表(自动建表,主键 id+name)
'lock_table' => 'kode_session_locks', // 分布式锁表
'lock_timeout' => 10, // 锁超时(秒)
]);
$manager = new SessionManager([
'default' => 'database',
'drivers' => [
'database' => [
'dsn' => 'sqlite:/path/to/sessions.db',
'table' => 'kode_sessions',
],
],
]);
$manager = new SessionManager([
'default' => 'file',
'drivers' => [
'file' => [
'path' => '/tmp/sessions',
'encrypted' => true, // 开启透明加密
'secret' => 'your-strong-secret', // 任意长度,内部经 PBKDF2 衍生为 32 字节密钥
],
],
]);
$manager = new SessionManager([
'default' => 'file',
'drivers' => [
'file' => [
'path' => '/tmp/sessions',
'compress' => true, // 开启透明压缩
'compression_level' => 6, // 0~9,默认 -1(zlib 默认级别),数值越大体积越小、越慢
],
],
]);
$session->getInt('views'); // int:兼容 int / 数值字符串 / bool
$session->getFloat('price'); // float:兼容 float / int / 数值字符串 / bool
$session->getBool('active'); // bool:兼容 bool / 数值 / "true"/"false"/"yes"/"no" 等
$session->getString('name'); // string:兼容 string / int / float / bool
$session->getArray('items'); // array:仅当存储值本身是数组时返回,否则回退默认值
$session->set('a', 1);
$session->set('b', 2);
$session->delete('c');
// 此刻另一会话尚读不到本次写入(未落盘)
// ...
$session->save(); // 脏键批量写入、删除键逐条删除,仅一次落盘
$middleware = new SessionMiddleware($manager, [
'name' => 'KODE_SESSION',
'lifetime' => 3600,
'path' => '/',
'secure' => false,
'http_only' => true,
'gc_probability' => 10, // 触发分子(默认 10,即 ~10% 请求触发 GC)
'gc_divisor' => 100, // 触发分母(默认 100)
]);
$manager = new SessionManager([
'default' => 'file',
'gc_probability' => 10, // 全局默认触发分子
'gc_divisor' => 100, // 全局默认触发分母
'gc_lifetime' => 3600, // 全局默认 GC 生命周期(0 表示取 session lifetime)
'drivers' => [...],
]);
$manager->setGcConfig(10, 100, 3600); // probability, divisor, lifetime
$manager = new SessionManager([
'default' => 'file',
'drivers' => [
'file' => [
'path' => '/tmp/sessions',
'prefix' => 'kode_sess_',
],
'redis' => [
'prefix' => 'kode_sess_',
'redis' => [
'host' => '127.0.0.1',
'port' => 6379,
],
],
'cookie' => [
'name' => 'kode_session',
'lifetime' => 3600,
],
],
]);
$middleware = new SessionMiddleware($manager, [
'driver' => 'file',
'name' => 'KODE_SESSION',
'lifetime' => 3600,
'path' => '/',
'domain' => null,
'secure' => false,
'http_only' => true,
'auto_start' => true,
]);
$session->start(); // 启动 session
$session->close(); // 关闭 session
$session->destroy(); // 销毁 session
$session->regenerate(); // 重新生成 session ID
$session->getId(); // 获取 session ID
$session->getName(); // 获取 session 名称
$session->isStarted(); // 检查是否已启动
$session->set('key', 'value'); // 设置值
$session->get('key'); // 获取值
$session->get('key', 'default'); // 获取值,不存在则返回默认值
$session->has('key'); // 检查是否存在(值为 null 也算存在)
$session->delete('key'); // 删除
$session->clear(); // 清空所有数据
$session->all(); // 获取所有数据
$session->pull('key'); // 获取并删除
$session->isDirty(); // 是否存在待落盘的变更(set/delete 之后、save 之前为 true)
$session->hasChanges(); // isDirty 的别名
$session->push('list', 'a'); // 向数组键追加值(自动初始化为数组)
$session->increment('counter'); // 自增 1,返回结果(非数字按 0 处理)
$session->increment('counter', 5);
$session->decrement('counter'); // 自减 1
$session->only(['a', 'b']); // 仅返回指定键
$session->except(['a']); // 排除指定键
$session->replace(['x' => 1]); // 整体替换为新数据
$session->forget('key'); // 删除单个键
$session->forget(['a', 'b']); // 批量删除
$session->flush(); // 清空(clear 的别名)
$session->flash('success', '操作成功'); // 下一请求可用,之后自动删除
$session->flash('tip', null); // 显式 null 也可存储(区分「未设置」)
$session->now('temp', '仅本请求'); // 仅当前请求可用,下一请求即失效
$session->old('success'); // 读取上一次请求的闪存
$session->keep(['success']); // 保留指定闪存多存活一轮(重定向场景)
$session->retainFlash(); // 保留全部闪存多存活一轮
$session->flushFlash(); // 清空所有闪存数据
$session->ageFlash(); // 将新闪存转为旧闪存
$session->setError('email', '邮箱格式不正确');
$session->hasError('email');
$session->getError('email');
$session->setSuccess('saved', '保存成功');
$session->hasSuccess('saved');
$token = $session->token(); // 获取 CSRF token
$session->token($newToken); // 设置 token
$session->verifyCsrfToken($token); // 验证 token
$manager->make($id, $config); // 创建 session
$manager->fromRequest($config); // 从请求创建(自动获取 session ID)
$manager->getDriver($name); // 获取驱动
$manager->createId(); // 创建新 session ID
$manager->getConfig('key'); // 获取配置
$manager->setConfig('key', $value); // 设置配置
$manager->gc($maxLifetime, $config); // 手动触发垃圾回收(默认驱动,可覆盖 config)
use Kode\Session\Support\FiberSessionStorage;
$fiber = new \Fiber(function () {
$session = FiberSessionStorage::get('session');
if ($session === null) {
return;
}
$session->set('user_id', 123);
});
$fiber->start();
use Kode\Session\Support\ContextSession;
$session = $manager->make($sessionId);
$session->start();
ContextSession::setSession($session);
ContextSession::set('request_id', uniqid());
$fiber = new \Fiber(function () {
$session = ContextSession::getSession();
$requestId = ContextSession::get('request_id');
var_dump($requestId);
});
$fiber->start();
use Kode\Session\Support\ParallelSession;
$parallel = new ParallelSession($manager, [
'driver' => 'redis',
]);
$parallel->create($sessionId);
$result = $parallel->withLock(function ($session) {
return $session->get('counter');
}, 10);
$result = $parallel->fork(function ($session) {
$session->set('worker_id', getmypid());
return $session->get('worker_id');
}, ['shared_data' => 'value']);
class Application
{
protected SessionManager $session;
public function handleRequest($request)
{
$this->session = $this->sessionManager->fromRequest([
'name' => 'APP_SESSION',
'lifetime' => 3600,
]);
$this->session->start();
}
public function terminate($response)
{
if ($this->session?->isStarted()) {
$this->session->save();
$this->session->close();
}
}
}
use Kode\Session\Contract\Driver;
class CustomDriver implements Driver
{
public function __construct(array $config = [])
{
}
public function get(string $id, string $name, mixed $default = null): mixed
{
}
public function set(string $id, string $name, mixed $value, int $lifetime = 0): bool
{
}
public function setMultiple(string $id, array $values, int $lifetime = 0): bool
{
}
public function delete(string $id, string $name): bool
{
}
public function has(string $id, string $name): bool
{
}
public function exists(string $id): bool
{
}
public function clear(string $id): bool
{
}
public function pull(string $id, string $name, mixed $default = null): mixed
{
}
public function remember(string $id, string $name, callable $callback, int $lifetime = 0): mixed
{
}
public function migrate(string $fromId, string $toId, bool $delete = true): bool
{
}
public function open(string $id): bool
{
}
public function close(string $id): bool
{
}
public function destroy(string $id): bool
{
}
public function gc(int $maxLifetime): int
{
}
public function all(string $id): array
{
}
public function generateId(): string
{
}
public function acquireLock(string $id, ?int $timeout = null): bool
{
}
public function releaseLock(string $id): bool
{
}
}
$manager->extend('custom', function (array $config) {
return new CustomDriver($config);
});