安装
composer require firebase/php-jwt
文档:https://github.com/firebase/php-jwt
<?php require __DIR__ . '/../vendor/autoload.php'; use Firebase\JWT\JWT; use Firebase\JWT\ExpiredException; $key = "example_key"; $time = time(); $data = [ 'id'=> 1, 'username'=> 'Tom' ]; $payload = array( "iat" => $time, // 签发时间 "ext" => $time, // 过期时间 "data"=> $data // 携带数据 ); $jwt = JWT::encode($payload, $key); echo $jwt; // 正常的jwt $decoded = JWT::decode($jwt, $key, array('HS256')); print_r($decoded); //[iat] => 1622605592 //[ext] => 1622605592 //[data] => stdClass Object // ( // [id] => 1 // [username] => Tom // ) // 异常捕获 $jwt = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE2MjI2MDUzNDUsImV4dCI6MTYyMjYwNTM0NSwiZGF0YSI6eyJpZCI6MSwidXNlcm5hbWUiOiJUb20ifX0.Jgp1JBPngj0lgmFpMty7C76mWwtFQVoLvQtGsN5LcpgstdClass Object'; try { $decoded = JWT::decode($jwt, $key, array('HS256')); }catch (ExpiredException $e){ echo 'token已过期'; }catch (\Exception $e){ echo 'token无效'; } print_r($decoded);