Home > Backend Development > PHP Problem > How to implement Token verification in PHP

How to implement Token verification in PHP

Guanhui
Release: 2023-03-01 07:52:01
Original
4559 people have browsed it

How to implement Token verification in PHP

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[&#39;code&#39;]=&#39;400&#39;;
        $msg[&#39;msg&#39;]=&#39;非法请求&#39;;
        return json_encode($msg,JSON_UNESCAPED_UNICODE);
    }
    //对比token
    $explode = explode(&#39;.&#39;,$token);
    //以.分割token为数组
    if(!empty($explode[0]) && !empty($explode[1]) && !empty($explode[2]) && !empty($explode[3]) ) {
        $info = $explode[0].&#39;.&#39;.$explode[1].&#39;.&#39;.$explode[2];
        //信息部分
        $true_signature = hash_hmac(&#39;md5&#39;,$info,&#39;siasqr&#39;);
        //正确的签名
        if(time() > $explode[2]) {
            $msg[&#39;code&#39;]=&#39;401&#39;;
            $msg[&#39;msg&#39;]=&#39;Token已过期,请重新登录&#39;;
            return json_encode($msg,JSON_UNESCAPED_UNICODE);
        }
        if ($true_signature == $explode[3]) {
            $msg[&#39;code&#39;]=&#39;200&#39;;
            $msg[&#39;msg&#39;]=&#39;Token合法&#39;;
            return json_encode($msg,JSON_UNESCAPED_UNICODE);
        } else {
            $msg[&#39;code&#39;]=&#39;400&#39;;
            $msg[&#39;msg&#39;]=&#39;Token不合法&#39;;
            return json_encode($msg,JSON_UNESCAPED_UNICODE);
        }
    } else {
        $msg[&#39;code&#39;]=&#39;400&#39;;
        $msg[&#39;msg&#39;]=&#39;Token不合法&#39;;
        return json_encode($msg,JSON_UNESCAPED_UNICODE);
    }
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template