PHP中ThinkPhp框架的token使用

在做登录信息核对时,面对源源不断的数据比对,都会给服务器造成一定的压力。对于我们常用的ThinkPhp框架也会有这样的困扰。不过有一种方法可以解决这类问题,那就是Token的作用。

一、token在ThinkPhp框架的使用

1.首先在数据库的 users 表中添加两个字段token、time_out

token 用于存储用户的 token

time_out 用于设置用户 token 的过期时间

2.创建函数

checkToekn($token)

函数用于检验 token 是否存在, 并且更新 token

publicfunctioncheckToken($token)
{
$user=new\app\index\model\Users();
$res=$user->field('time_out')->where('token',$token)->select();

if(!empty($res)){
//dump(time()-$res[0]['time_out']);
if(time()-$res[0]['time_out']>0){

return90003;//token长时间未使用而过期,需重新登陆
}
$new_time_out=time()+604800;//604800是七天
$res=$user->isUpdate(true)
->where('token',$token)
->update(['time_out'=>$new_time_out]);
if($res){

return90001;//token验证成功,time_out刷新成功,可以获取接口信息
}
}

return90002;//token错误验证失败
}

3.创建函数

douserLogin($username,$password)

用于验证用户名密码, 并登陆, 返回 token 信息

publicfunctiondouserLogin()
{
$user=new\app\index\model\Users();
$userisset=$user->where('username',$username)->find();
if($userisset==null){
returnjson_decode('{"user":"'.$username.'","code":"400","msg":"用户不存在"}');
}else{
$userpsisset=$user
->where('username',$username)
->where('password',sha1(md5($password)))->find();

if($userpsisset==null){
returnjson_decode('{"user":"'.$username.'","code":"401","msg":"密码错误"}');
}else{
//session('user',$username);
$token=$this->makeToken();
$time_out=strtotime("+7days");
$userinfo=['time_out'=>$new_time_out,
'token'=>$token];
$res=$user->isUpdate(true)
->where('username',$username)
->update($userinfo);
if($res){
returnjson_decode('{"user":"'.$username.'","toekn":'.$token.'"code":"0","msg":"登录成功"}');
}
}
}
}

二、Token的概念

token是客户端频繁向服务器端请求数据,服务器频繁的去数据库查询用户名和密码判断用户名和密码正确与否,并作出相应的提示,在这样的背景下,token便应运而生了。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。