<?php
session_start();
?>
<?php
// 存储会话数据
$_SESSION['username'] = 'John Doe';
$_SESSION['email'] = 'john@example.com';
?>
<?php
// 访问会话数据
echo $_SESSION['username']; // 输出: John Doe
echo $_SESSION['email']; // 输出: john@example.com
?>
<?php
// 删除某项会话数据
unset($_SESSION['email']);
?>
<?php
// 注销整个会话
session_destroy();
?>
<?php
// 设置会话有效期为1小时
$expire_time = 3600;
session_set_cookie_params($expire_time);
session_start();
?>
启用 HTTPS,避免会话数据在网络中明文传输。
不直接存储敏感信息如密码,可存储令牌或ID引用。
使用 session_regenerate_id() 在登录等关键操作时更新会话ID,防止固定会话攻击。
定期清除过期会话,减少数据泄露风险。
<?php
session_start();
// 存储会话数据
$_SESSION['username'] = 'John Doe';
$_SESSION['email'] = 'john@example.com';
// 访问会话数据
echo $_SESSION['username']; // 输出: John Doe
echo $_SESSION['email']; // 输出: john@example.com
// 删除会话数据
unset($_SESSION['email']);
// 注销会话
session_destroy();
// 设置会话失效时间为一小时
$expire_time = 3600;
session_set_cookie_params($expire_time);
session_start();
?>