ThinkPhp5 实现token登陆的学习笔记分享

简介前几天用thinkphp5做项目需要用到token登陆,在此整理了一下分享给大家,需要的可以研究研究。一、首先在数据库的users表中添加两个字段1、token2、time_outtoken【用于存储用户的tokentime_out用于设置用户token的过期时间首先创建函数:checkToekn($token)函数用于检验token是否存在,并且更新token】publicfunctionche

  

前几天用thinkphp5做项目需要用到token登陆,在此整理了一下分享给大家,需要的可以研究研究。

一、首先在数据库的 users 表中添加两个字段

1、token

2、time_outtoken 【用于存储用户的 tokentime_out 用于设置用户 token 的过期时间首先创建函数: checkToekn($token)函数用于检验 token 是否存在, 并且更新 token】

publicfunctioncheckToken($token){$user=newappindexmodelUsers();$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错误验证失败}

创建函数:douserLogin($username,$password)用于验证用户名密码, 并登陆, 返回 token 信息

publicfunctiondouserLogin(){$user=newappindexmodelUsers();$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":"登录成功"}');}}}}

创建函数:makeToekn()创建 token

privatefunctionmakeToken(){$str=md5(uniqid(md5(microtime(true)),true));//生成一个不会重复的字符串$str=sha1($str);//加密return$str;}

使用的时候,在需要验证的地方加上如下内容即可判断是否登陆

$login=newappindexcontrollerLogin;$res=$login->checkToken($token);if($res==90001){echo'ok';}elseif($res==90002){echo'err';}elseif($res==90003){echo'relogin';}

这样基本上就可以了,希望对大家有所帮助。

下载链接:网站源码/小程序源码/网站模板下载

版权声明

   站内部分内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供网络资源分享服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请 联系我们 一经核实,立即删除。并对发布账号进行永久封禁处理。在为用户提供最好的产品同时,保证优秀的服务质量。


本站仅提供信息存储空间,不拥有所有权,不承担相关法律责任。

给TA打赏
共{{data.count}}人
人已打赏
网站技巧

解决WordPress评论加强:防止游客冒充站长回复别人的办法

2024-9-19 19:44:31

网站技巧

关于WordPress之防御cc攻击(频繁F5刷新)的办法

2024-9-19 19:44:33

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索