这篇文章快速介绍 windows 系统 与 CentOS 系统快速安装 PHP 7 或者 PHP 8,相关版本安装原理类同。本篇文章的重点在于 JWT 使用,不纠结于 PHP 版本。
本篇文章,没有通过 PHP 官方下载安装。而是选择了业内非常出名的第三方一键安装包WampServer。WampServer是一款专为Windows操作系统设计的集成开发环境,主要用于搭建本地Web服务器,支持动态网站或应用程序的开发与测试。它将Apache Web服务器、PHP解释器和MySQL数据库整合在一起,通过图形化界面简化了安装、配置和管理流程。
步骤 1:通过浏览器 访问 https://www.wampserver.com/
步骤 2:就在主页,找到安装文件的下载地址。直接点击链接,通过浏览器下载到本地安装。例如文件名称: WampServer 64 bits (x64) 3.3.7.exe
步骤 3:鼠标左键点击exe文件,按照提示安装完成。点击桌面快捷方式Wampserver64,等待任务栏出现
绿色图标,表示启动成功了。
最后,通过浏览器访问URL地址,http://localhost/ 或者 http://127.0.0.1/ 出现 Wampserver 本地首页(Homepage)!
步骤 1:您可以提前搜索本机源是否有 PHP 安装包。如果您熟悉本机 PHP 安装版本,这个步骤可以省略。
yum search php
步骤 2:根据 search 结果,挑选 PHP 安装包,且运行安装命令。
yum install php.x86_64
步骤 3:验证 PHP 版本:
php -v
使用 Composer 管理依赖项并下载 PHP-JWT。关于 PHP-JWT 更多信息,请访问 GitHub 地址 https://github.com/firebase/php-jwt/
composer require firebase/php-jwt
该示例使用的对称加密签名算法,示例代码如下所示:
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
$key = 'example_key';
$payload = [
'iss' => 'http://example.org',
'aud' => 'http://example.com',
'iat' => 1356999524,
'nbf' => 1357000000
];
/**
* IMPORTANT:
* You must specify supported algorithms for your application. See
* https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
* for a list of spec-compliant algorithms.
*/
$jwt = JWT::encode($payload, $key, 'HS256');
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
print_r($decoded);
// Pass a stdClass in as the third parameter to get the decoded header values
$headers = new stdClass();
$decoded = JWT::decode($jwt, new Key($key, 'HS256'), $headers);
print_r($headers);
/*
NOTE: This will now be an object instead of an associative array. To get
an associative array, you will need to cast it as such:
*/
$decoded_array = (array) $decoded;
/**
* You can add a leeway to account for when there is a clock skew times between
* the signing and verifying servers. It is recommended that this leeway should
* not be bigger than a few minutes.
*
* Source: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef
*/
JWT::$leeway = 60; // $leeway in seconds
$decoded = JWT::decode($jwt, new Key($key, 'HS256'));
您可以把这段代码另存为一个PHP文件,例如 jwt.php,然后通过WebServer形式访问,或者命令行形式访问。以下是命令行测试:
php jwt.php