Current Location: Home> Latest Articles> <strong data-start="256" data-end="301">Translated and Optimized English Version:</strong>Complete Guide to Secure Authentication in PHP Using JWT

Translated and Optimized English Version:Complete Guide to Secure Authentication in PHP Using JWT

M66 2025-06-04

Introduction to JWT in PHP

JWT (JSON Web Token) is a widely-used open standard for authentication and secure data exchange. A JWT is composed of three parts: the header, payload, and signature. It allows secure transmission of identity information between the client and the server.

Setting Up JWT in a PHP Project

Integrating JWT in a PHP application is straightforward with the help of the Firebase JWT library. Use Composer to install the package:

composer require firebase/php-jwt

Example: Generating a JWT

The following PHP snippet demonstrates how to generate a JWT token with basic user information:


<?php

require_once 'vendor/autoload.php';

use Firebase\JWT\JWT;

// Define your secret key
$key = "your_secret_key";

// Create the payload with user data
$payload = array(
    "iss" => "example.org",
    "sub" => "user_id",
    "name" => "John Doe"
);

// Encode the payload into a JWT
$jwt = JWT::encode($payload, $key);
echo $jwt;

?>

In this example, we load the Firebase JWT library, define a secret key, create a payload with user details, and generate a JWT using the JWT::encode() function.

Example: Verifying a JWT

To authenticate user requests, you need to verify the provided JWT. Here’s how to do it:


<?php

require_once 'vendor/autoload.php';

use Firebase\JWT\JWT;

// Received JWT (e.g., from request headers)
$jwt = "JWT";

// The same secret key used to encode the token
$key = "your_secret_key";

try {
    // Decode and validate the JWT
    $decoded = JWT::decode($jwt, $key, array('HS256'));

    // Output decoded user information
    echo "User ID: " . $decoded->sub . "<br>";
    echo "Username: " . $decoded->name . "<br>";

} catch (Exception $e) {
    echo 'Verification failed: ' . $e->getMessage();
}

?>

In this code, the JWT is decoded using the same key. If the token is valid, the decoded information is displayed. If not, an error message is shown.

Conclusion

JWT provides a powerful and efficient way to handle authentication and authorization in PHP applications. With the Firebase JWT PHP library, developers can easily generate and verify secure tokens, enabling robust user session management without relying on traditional session-based methods.