通过用户反馈服务器在使用时,如果网站过多或者并发过大,php自带的session可能会失效于是就有个了这个数据库版本,模拟session功能,今天把主要逻辑代码分享出来注意:代码中的DB类如果和你的程序不兼容需要自己改一下哦// +----------------------------------------------------------------------// | Nmae:Session数据库版 根据cookie生成设备标识,可替换本地服务器session过多出错问题// +----------------------------------------------------------------------// | Author: 沉梦执于梦 857285711 <blog.chenmyun.com>// +----------------------------------------------------------------------// | Date: 2020/10/16// +----------------------------------------------------------------------class Session{ /** * 设置Session * @param [type] $name [description] * @param [type] $value [description] * @param [type] $expire [description] */ public static function set($name, $value, $expire = null) { global $DB; $userid = self::getUserId(); if ($expire === null || $expire < time()) { $expire = time() + 3600; } try { $row = $DB->get_row("SELECT * FROM `auth_session` WHERE u= ? and k= ? limit 1", [$userid, $name]); if ($row != false && isset($row['id'])) { $data = [$value, $expire, $row['id']]; return $DB->query("UPDATE `auth_session` SET v= ?, e= ? WHERE `id`= ?", $data); } else { $sql = "INSERT INTO `auth_session` (`u`,`k`,`v`,`e`) VALUES (?, ?, ?, ?)"; $data = [$userid, $name, $value, $expire]; if ($DB->query($sql, $data)) { return true; } throw new \PDOException($DB->error()); } } catch (\PDOException $e) { die('数据库错误:' . $e->getMessage()); } catch (\Exception $e) { die('系统错误:' . $e->getMessage()); } } /** * 获取session * @param string $name session名称 * @return string */ public static function get($name = 'userid') { global $DB; $userid = self::getUserId(); $data = [$userid, $name]; $row = $DB->get_row("SELECT * FROM `auth_session` WHERE u= ? and k= ? limit 1", $data); if (is_array($row) && $row['e'] > time()) { return $row['v']; } return ''; } /** * 获取设备唯一标识 * @param boolean $update 是否刷新 */ public static function getUserId($update = false) { $userid = isset($_COOKIE['uid']) ? $_COOKIE['uid'] : null; if ($update || empty($userid) || !isset($_COOKIE['uid'])) { $userid = md5(uniqid(mt_rand(), 1) . time() . rand(1111, 9999) . x_real_ip()); setcookie('uid', $userid, time() + 86400 * 30, '/', null); } return $userid; } /** * 生成随机MD5字符串 * @return string */ public static function getRandString() { return md5(uniqid(mt_rand(), 1) . time() . rand(11111, 99999) . x_real_ip()); } /** * 清空当前设备cookie * @param [type] $name [description] * @return [type] [description] */ public static function checkDel($name) { $num = 0; if (is_array($_COOKIE)) { foreach ($_COOKIE as $key => $value) { if ($key == $name) { $num++; } } if ($num >= 2) { unset($_COOKIE[$name]); } } }}