更新時(shí)間:2018-10-26 來(lái)源:黑馬程序員技術(shù)社區(qū) 瀏覽量:
session入庫(kù)以及php高版本(7.2)下session入庫(kù)報(bào)錯(cuò)的解決辦法
我們?cè)趐hp7.0下,實(shí)現(xiàn)session入庫(kù),代碼如下:
<?php
//連接數(shù)據(jù)庫(kù)
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']="北京";
運(yùn)行一切正常,可是一旦切換到高版本,例如7.2下,就會(huì)報(bào)錯(cuò),Warning: session_start(): Failed to read session data: user (path: ) 或者是其他莫名的錯(cuò),解決辦法也很簡(jiǎn)單,只需要在read方法里面的return mysqli_fetch_row($res)[0],在返回之前做一下強(qiáng)制類型轉(zhuǎn)換即可,即改成return (string)mysqli_fetch_row($res)[0];但是沒強(qiáng)制轉(zhuǎn)換之前也是字符串,為什么就不行呢?嘿嘿,你如果到傳智來(lái),我就告訴你。
本文版權(quán)歸黑馬程序員PHP+H5全棧工程師培訓(xùn)學(xué)院所有,歡迎轉(zhuǎn)載,轉(zhuǎn)載請(qǐng)注明作者出處。謝謝!
作者:PHP+H5全棧工程師培訓(xùn)學(xué)院
首發(fā):http://java.itcast.cn/?skc