更新时间:2018-10-26 来源:黑马程序员技术社区 浏览量:
session入库以及php高版本(7.2)下session入库报错的解决办法
我们在php7.0下,实现session入库,代码如下:
<?php
//连接数据库
function conn(){
$link=mysqli_connect('localhost','root','aa','php1',3306);
mysqli_set_charset($link,'utf8');
return true;
}
function open(){
return conn();
}
function close(){
return true;
}
function read($sess_id){
global $link;
$sql = "select sess_value from sess where sess_id='{$sess_id}'";
$res=mysqli_query($link,$sql);
if(mysqli_fetch_row($res)[0]){
return mysqli_fetch_row($res)[0];
}
return '';
}
function write($sess_id,$sess_value){
global $link;
$time=time();
$sql="insert into sess values('{$sess_id}','{$sess_value}','{$time}')
on duplicate key update sess_value='{$sess_value}',sess_time='{$time}'";
return mysqli_query($link,$sql);
}
function delete($sess_id){
global $link;
$sql="delete from sess where sess_id='{$sess_id}'";
return mysqli_query($link,$sql);
}
function gc($lifetime){
global $link;
$nowtime=time();
$time=$nowtime-$lifetime;
$sql="delete from sess where sess_time<'{$time}'";
return mysqli_query($link,$sql);
}
session_set_save_handler('open','close','read','write','delete','gc');
session_start();
$_SESSION['name']="北京";
运行一切正常,可是一旦切换到高版本,例如7.2下,就会报错,Warning: session_start(): Failed to read session data: user (path: ) 或者是其他莫名的错,解决办法也很简单,只需要在read方法里面的return mysqli_fetch_row($res)[0],在返回之前做一下强制类型转换即可,即改成return (string)mysqli_fetch_row($res)[0];但是没强制转换之前也是字符串,为什么就不行呢?嘿嘿,你如果到传智来,我就告诉你。
本文版权归黑马程序员PHP+H5全栈工程师培训学院所有,欢迎转载,转载请注明作者出处。谢谢!