Welcome to our PHP JWT Generation tutorial! In this lesson, we'll guide you through the process of generating JSON Web Tokens (JWT) using PHP. By the end of this tutorial, you'll be able to create, verify, and handle JWT in your own projects. Let's dive in!
JSON Web Tokens (JWT) is a compact, URL-safe means of representing claims to enable authentication and information exchange between parties. They are widely used for securely transmitting data between parties as an alternative to session cookies.
To start generating JWT in PHP, we'll use the Firebase JWT library. First, let's install it via composer:
composer require firebase/php-jwtNow, let's create a simple JWT that contains user data.
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
$secret_key = "your_secret_key";
$issued_at = time();
$expiration_time = $issued_at + (60 * 60); // expires in 1 hour
$payload = array(
"iat" => $issued_at, // Issued At: time when the token was issued.
"exp" => $expiration_time, // Expiration Time: time when the token will expire.
"data" => array(
"user_id" => 123,
"username" => "example_user",
"email" => "example@example.com"
)
);
$jwt = JWT::encode($payload, $secret_key);
echo $jwt;Replace "your_secret_key" with your own secret key.
To decode a JWT, you can use the Firebase\JWT\JWT class again.
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Firebase\JWT\JWT;
$secret_key = "your_secret_key";
$jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoidGVzdF91c2VyIn0.EoU9Zv2F7RvLb57Uw2277TZf98_QkWgvXL-0qL_0GKjz"; // Sample JWT
try {
$decoded = JWT::decode($jwt, $secret_key, array('HS256'));
print_r($decoded);
} catch (Exception $e) {
echo $e->getMessage();
}Replace "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxMjMsInVzZXJuYW1lIjoidGVzdF91c2VyIn0.EoU9Zv2F7RvLb57Uw2277TZf98_QkWgvXL-0qL__0GKjz" with your own JWT.
What is the main purpose of JSON Web Tokens (JWT)?
That's it for our PHP JWT Generation tutorial! Practice the provided examples, explore more with the Firebase JWT library, and soon you'll be generating secure JWTs for your own projects. Happy coding! π»π