How PHP implements Token verification
First parse the Token; then verify whether it has expired based on the parsed information part, and if it has not expired, then The parsed information part is encrypted; finally, the encrypted data is compared with the parsed signature. If they are the same, the verification is successful.
Sample code:
<?php 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); } }
Recommended tutorial: "PHP Tutorial"
The above is the detailed content of How to implement Token verification in PHP. For more information, please follow other related articles on the PHP Chinese website!