PHP code example of chenbool / jwt

1. Go to this page and download the library: Download chenbool/jwt library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

chenbool / jwt example snippets



use \chenbool\JWT\JWT;

$key = "example_key";
$token = array(
    "iss" => "http://example.org", // 签发者
    "aud" => "http://example.com", // 接收方
    "iat" => 1356999524, // 签发时间
    "nbf" => time()+30, // 30秒后生效
    "exp" => time()+7200, // 2小时后过期
);

// 加密生成 Token
$jwt = JWT::encode($token, $key);

// 解密/验证 Token
$decoded = JWT::decode($jwt, $key, array('HS256'));
$decoded_array = (array) $decoded;
print_r($decoded);


try {
    JWT::$leeway = 60; // 时间偏移量
    $decoded = JWT::decode($jwt, $key, array('HS256'));
} catch(\chenbool\JWT\SignatureInvalidException $e) {  
    echo $e->getMessage(); // 签名不正确
} catch(\chenbool\JWT\BeforeValidException $e) {  
    echo $e->getMessage(); // Token 未生效
} catch(\chenbool\JWT\ExpiredException $e) {  
    echo $e->getMessage(); // Token 已过期
} catch(Exception $e) {  
    echo $e->getMessage(); // 其他错误
}

jwt/
├── src/                       # 源代码
│   ├── JWT.php               # 核心类
│   ├── BeforeValidException.php    # 未生效异常
│   ├── ExpiredException.php       # 过期异常
│   └── SignatureInvalidException.php # 签名无效异常
├── composer.json               # 依赖配置
├── LICENSE                    # 许可证
└── README.md