PHP7 使用session_set_save_handler

项目原本是在php5.4.45-nts运行的,后面升级到PHP7,发现session总是存储不了

我的session是通过session_set_save_handler自定义存储到数据库中

正常的seesion过程应该是open->read->write->close

升级PHP后变成了open->read->close

所以就去检查了read函数

public function read($sessID)
	{
		$sql = 'SELECT session_data AS d FROM ' . $this->prefix . 'sessions WHERE session_id = \'' . $sessID . '\'   AND session_expires >' . TIMES;
		$row = $this->db->get_one($sql);

		if ($row) {
			$data = $row['d'];
			return $data;
		}
		return false;
	}

在没有数据的时候 retrun false;

最终确定问题也是这个return false;修改为return '';即可

具体原因我也不是很清楚,应该是return false导致session自己直接跳过write了

附上完整的重写函数:

lifeTime = 3600;
		return true;
	}
	public function close()
	{
		$this->gc(ini_get('session.gc_maxlifetime'));
		return true;
	}
	public function read($sessID)
	{
		$sql = 'SELECT session_data AS d FROM ' . $this->prefix . 'sessions WHERE session_id = \'' . $sessID . '\'   AND session_expires >' . TIMES;
		$row = $this->db->get_one($sql);

		if ($row) {
			$data = $row['d'];
			return $data;
		}
		return '';
	}
	public function write($sessID, $sessData)
	{
		if (!($sessData)) {
			return false;
		}
		$newExp = TIMES + $this->lifeTime;
		$sql = 'SELECT * FROM ' . $this->prefix . 'sessions WHERE session_id = \'' . $sessID . '\'';
		$num = $this->db->get_num($sql);

		if ($num) {
			$this->db->query('UPDATE ' . $this->prefix . 'sessions  SET session_expires = \'' . $newExp . '\', session_data = \'' . $sessData . '\' WHERE session_id = \'' . $sessID . '\'');

			if ($this->db->affected_rows()) {
				return true;
			}
		}
		else {
			$this->db->query('INSERT INTO ' . $this->prefix . 'sessions (  session_id, session_expires, session_data)  VALUES( \'' . $sessID . '\', \'' . $newExp . '\',  \'' . $sessData . '\')');

			if ($this->db->affected_rows()) {
				return true;
			}
		}
		return false;
	}
	public function destroy($sessID)
	{
		$this->db->query('DELETE FROM ' . $this->prefix . 'sessions WHERE session_id = \'' . $sessID . '\'');

		if ($this->db->affected_rows()) {
			return true;
		}
		return false;
	}
	public function gc($sessMaxLifeTime)
	{
		$this->db->query('DELETE FROM ' . $this->prefix . 'sessions WHERE session_expires < ' . TIMES);
		return true;
	}
	public function __destruct()
	{
		session_write_close();
	}
}

?>

你可能感兴趣的:(PHP)