Session 基础
概述
PHP Session 提供了在多个页面请求之间保持用户数据的能力。Session 数据存储在服务器端,通过 Cookie 中的 Session ID 关联到特定用户。session_start() 启动会话,$_SESSION 存取会话数据,session_id() 获取/设置会话 ID。
适用场景
- 用户登录状态管理
- 购物车数据存储
- 多步表单数据暂存
- 临时数据传递
基础概念
Session 工作流程
1. 客户端请求 → session_start() → 检查 $_COOKIE[session.name]
↓
2. 无 Session ID → 创建新 Session → 生成 Session ID
↓
3. 有 Session ID → 加载对应 Session 数据 → 填充 $_SESSION
↓
4. 脚本执行结束 → Session 数据序列化保存 → 发送 Set-Cookie 头核心函数
| 函数 | 功能 |
|---|---|
session_start() | 启动/恢复会话 |
session_id() | 获取/设置 Session ID |
session_regenerate_id() | 重新生成 Session ID |
session_destroy() | 销毁会话数据 |
session_unset() | 清空 $_SESSION |
session_name() | 获取/设置会话名称 |
session_encode() | 编码会话数据 |
session_decode() | 解码会话数据 |
PHP 8.0+ 变更
session_start() 可以接受选项数组参数。session_id() 的返回值类型更严格。
语法与代码示例
基本 Session 使用
php
<?php
// 启动 Session(必须在输出之前)
session_start();
// 设置 Session 数据
$_SESSION['user_id'] = 12345;
$_SESSION['username'] = 'Alice';
$_SESSION['login_time'] = time();
$_SESSION['preferences'] = ['theme' => 'dark', 'lang' => 'zh-CN'];
// 读取 Session 数据
$userId = $_SESSION['user_id'] ?? null;
$username = $_SESSION['username'] ?? 'Guest';
echo "用户: {$username} (ID: {$userId})\n";
echo "登录时间: " . date('Y-m-d H:i:s', $_SESSION['login_time']) . "\n";Session ID 管理
php
<?php
session_start();
// 获取当前 Session ID
$sid = session_id();
echo "当前 Session ID: {$sid}\n";
// 设置 Session ID(必须在 session_start 之前)
$newSid = session_create_id(); // PHP 7.1+ 生成新的安全 ID
// session_id($newSid); // 不能在 session_start 后使用
// 重新生成 Session ID(安全措施,防止 session fixation)
session_regenerate_id(true); // true 删除旧 Session 文件
echo "新 Session ID: " . session_id() . "\n";
// PHP 7.1+ 自定义前缀
$prefix = 'myapp_';
$sid = session_create_id($prefix);
// session_id($sid); // 使用前设置
// session_start();销毁 Session
php
<?php
session_start();
// 方式一:完全销毁(推荐用于登出)
$_SESSION = []; // 清空数据
session_regenerate_id(true); // 重新生成 ID
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(
session_name(),
'',
time() - 42000,
$params['path'],
$params['domain'],
$params['secure'],
$params['httponly']
);
}
session_destroy();
// 方式二:仅清空数据
session_unset(); // 等同于 $_SESSION = []Session 数据存储位置
php
<?php
// Session 默认存储在服务器文件中
// 路径由 session.save_path 配置决定
echo "Session 保存路径: " . session_save_path() . PHP_EOL;
echo "Session 名称: " . session_name() . PHP_EOL;
echo "Session ID: " . session_id() . PHP_EOL;
// 查看 Session 配置
$settings = [
'save_handler' => ini_get('session.save_handler'),
'save_path' => ini_get('session.save_path'),
'name' => ini_get('session.name'),
'cookie_lifetime' => ini_get('session.cookie_lifetime'),
'cookie_path' => ini_get('session.cookie_path'),
'cookie_httponly' => ini_get('session.cookie_httponly'),
'cookie_secure' => ini_get('session.cookie_secure'),
'gc_maxlifetime' => ini_get('session.gc_maxlifetime'),
];
print_r($settings);实战示例
登录状态管理
php
<?php
declare(strict_types=1);
class AuthManager
{
public function __construct()
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
}
public function login(int $userId, string $username): void
{
// 防止 session fixation
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
$_SESSION['username'] = $username;
$_SESSION['ip'] = $_SERVER['REMOTE_ADDR'];
$_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? '';
$_SESSION['login_time'] = time();
$_SESSION['last_activity'] = time();
}
public function isLoggedIn(): bool
{
return isset($_SESSION['user_id']);
}
public function getUserId(): ?int
{
return $_SESSION['user_id'] ?? null;
}
public function logout(): void
{
$_SESSION = [];
if (ini_get('session.use_cookies')) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params['path'], $params['domain'],
$params['secure'], $params['httponly']
);
}
session_destroy();
}
/**
* 检查会话是否被劫持(指纹验证)
*/
public function validateFingerprint(): bool
{
if (!isset($_SESSION['ip'], $_SESSION['user_agent'])) {
return false;
}
$ipMatch = $_SESSION['ip'] === $_SERVER['REMOTE_ADDR'];
$uaMatch = $_SESSION['user_agent'] === ($_SERVER['HTTP_USER_AGENT'] ?? '');
return $ipMatch && $uaMatch;
}
/**
* 更新最后活动时间
*/
public function touch(): void
{
$_SESSION['last_activity'] = time();
}
}
// 使用
$auth = new AuthManager();
$auth->login(1, 'admin');
echo "已登录用户 ID: " . $auth->getUserId() . PHP_EOL;多步表单
php
<?php
declare(strict_types=1);
class MultiStepForm
{
private int $currentStep;
private int $totalSteps = 3;
public function __construct()
{
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
$this->currentStep = $_SESSION['form_step'] ?? 1;
}
public function getCurrentStep(): int
{
return $this->currentStep;
}
public function submit(array $data): void
{
$_SESSION["form_step_{$this->currentStep}"] = $data;
if ($this->currentStep < $this->totalSteps) {
$this->currentStep++;
$_SESSION['form_step'] = $this->currentStep;
}
}
public function getData(int $step): array
{
return $_SESSION["form_step_{$step}"] ?? [];
}
public function getAllData(): array
{
$data = [];
for ($i = 1; $i <= $this->totalSteps; $i++) {
$data = array_merge($data, $this->getData($i));
}
return $data;
}
public function reset(): void
{
for ($i = 1; $i <= $this->totalSteps; $i++) {
unset($_SESSION["form_step_{$i}"]);
}
unset($_SESSION['form_step']);
$this->currentStep = 1;
}
}注意事项
session_start 必须在输出前
php
<?php
// session_start 发送 Set-Cookie 头,必须在输出前调用
// 不好
echo "Hello";
session_start(); // Warning!
// 好
session_start();
echo "Hello";
// PHP 8.0+ 可以用 options 避免部分问题
// session_start(['read_and_close' => true]); // 只读模式并发 Session 锁定
php
<?php
// PHP 默认锁定 Session 文件,防止并发写入
// 但这也意味着同一用户的并发请求会被串行化
// 解决方案:PHP 7.0+ 使用 read_and_close
session_start([
'read_and_close' => true, // 读取后立即关闭,不锁定
]);
// 如果不需要修改 Session
$userId = $_SESSION['user_id'] ?? null;
// 或者使用 SessionHandlerInterface 自定义存储(Redis 等)最佳实践
1. 及时销毁不需要的 Session
php
<?php
// 登出时完整销毁
function secureLogout(): void
{
session_start();
$_SESSION = [];
session_regenerate_id(true);
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params['path'], $params['domain'],
$params['secure'], $params['httponly']
);
session_destroy();
}2. 使用 session_regenerate_id 防止 fixation
php
<?php
// 每次登录成功后重新生成 Session ID
session_start();
if (authenticate($username, $password)) {
session_regenerate_id(true);
$_SESSION['user_id'] = $userId;
}进阶用法
调试与测试技巧
php
<?php
declare(strict_types=1);
// 单元测试辅助函数
function createTestResource(): mixed
{
return match (true) {
default => new stdClass(),
};
}
// 调试输出函数
function debugOutput(mixed , string = ''): void
{
= ? ": " : '';
.= print_r(, true);
fwrite(STDERR, . "\n");
}
// 性能基准测试
function benchmark(callable , int = 1000): float
{
= hrtime(true);
for ($i = 0; $i < $iterations; $i++) {
$fn();
}
return (hrtime(true) - $start) / 1e9;
}日志记录实践
php
<?php
declare(strict_types=1);
/**
* 简易日志记录器
*/
class SimpleLogger
{
private string $logFile;
private string $level = 'INFO';
public function __construct(string $logFile)
{
$this->logFile = $logFile;
}
public function info(string $message, array $context = []): void
{
$this->log('INFO', $message, $context);
}
public function warning(string $message, array $context = []): void
{
$this->log('WARNING', $message, $context);
}
public function error(string $message, array $context = []): void
{
$this->log('ERROR', $message, $context);
}
private function log(string $level, string $message, array $context): void
{
$timestamp = date('Y-m-d H:i:s');
$contextStr = $context ? ' ' . json_encode($context, JSON_UNESCAPED_UNICODE) : '';
$line = "[{$timestamp}] [{$level}] {$message}{$contextStr}\n";
file_put_contents($this->logFile, $line, FILE_APPEND | LOCK_EX);
}
}配置与环境检测
php
<?php
declare(strict_types=1);
// 环境检测工具
class EnvironmentChecker
{
public static function checkRequirements(array $requirements): array
{
$results = [];
foreach ($requirements as $name => $check) {
$results[$name] = is_callable($check) ? $check() : false;
}
return $results;
}
public static function getSystemInfo(): array
{
return [
'php_version' => PHP_VERSION,
'os' => PHP_OS,
'sapi' => PHP_SAPI,
'memory_limit' => ini_get('memory_limit'),
'max_execution_time' => ini_get('max_execution_time'),
'loaded_extensions' => get_loaded_extensions(),
];
}
}常见问题排查
| 问题 | 可能原因 | 解决方案 |
|---|---|---|
| 连接超时 | 网络问题/配置错误 | 检查配置,增加超时时间 |
| 权限不足 | 文件/目录权限 | 使用 chmod/chown 修正 |
| 性能下降 | 索引缺失/数据量大 | 添加索引,优化查询 |
| 数据不一致 | 并发冲突/事务残留 | 使用锁机制和事务 |
| 内存溢出 | 大数据集/未释放资源 | 增大内存限制,分批处理 |
故障排除步骤
- 检查错误日志和异常信息
- 确认配置和环境是否正确
- 使用调试工具逐步排查
- 参考官方文档查找已知问题
版本兼容性说明
| 功能 | 最低版本 | 说明 |
|---|---|---|
| 基础功能 | PHP 8.1 | 本文档基准版本 |
| 只读属性 | PHP 8.1 | public readonly 修饰符 |
| 枚举类型 | PHP 8.1 | enum 类型和 match 表达式 |
| Fiber | PHP 8.1 | 协程/轻量级并发 |
| 命名参数 | PHP 8.0 | foo(arg_name: value) |
| 联合类型 | PHP 8.0 | `int |
| Null 安全运算符 | PHP 8.0 | $obj?->method() |
| 析构器 promotion | PHP 8.0 | __construct(public $x) |
php
<?php
declare(strict_types=1);
// 版本兼容性检测
function ensureVersion(string $minVersion): void
{
if (version_compare(PHP_VERSION, $minVersion, '<')) {
throw new RuntimeException(
sprintf('需要 PHP %s+, 当前版本: %s', $minVersion, PHP_VERSION)
);
}
}
ensureVersion('8.1.0');