thinkphp6 token(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便应运而生了 。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!