php实现token

//生成token

public static function setToken($userInfo){
        $admin = $userInfo->name;
        $time = time();
        $end_time =time()+86400;
        $info = $admin.".".$time.".".$end_time;
        $signature = hash_hmac('md5',$info,'siasqr');
        $token =$info.".".$signature;
        return $token;
    }

//验证token

public function check_token($token)
    {
        /**** api传来的token ****/
        if(!isset($token) || empty($token))
        {
            $msg['code']='400';
            $msg['msg']='非法请求';
            return json_encode($msg,JSON_UNESCAPED_UNICODE);
        }
        //对比token
        $explode = explode('.',$token);//以.分割token为数组
        if(!empty($explode[0]) && !empty($explode[1]) && !empty($explode[2]) && !empty($explode[3]) )
        {
            $info = $explode[0].'.'.$explode[1].'.'.$explode[2];//信息部分
            $true_signature = hash_hmac('md5',$info,'siasqr');//正确的签名
            if(time() > $explode[2])
            {
                $msg['code']='401';
                $msg['msg']='Token已过期,请重新登录';
                return json_encode($msg,JSON_UNESCAPED_UNICODE);
            }
            if ($true_signature == $explode[3])
            {
                $msg['code']='200';
                $msg['msg']='Token合法';
                return json_encode($msg,JSON_UNESCAPED_UNICODE);
            }
            else
            {
                $msg['code']='400';
                $msg['msg']='Token不合法';
                return json_encode($msg,JSON_UNESCAPED_UNICODE);
            }
        }
        else
        {
            $msg['code']='400';
            $msg['msg']='Token不合法';
            return json_encode($msg,JSON_UNESCAPED_UNICODE);
        }

    }

你可能感兴趣的:(php实现token)