To generate and validate JWT without using any existing package in PHP, you'll need to understand the structure and components of a JWT, and implement the necessary logic yourself. Here's a detailed explanation of how you can achieve this:


Generate JWT on Login When a user successfully logs in, you need to generate a JWT and send it back to the client.

Follow these steps to generate a JWT:

1. Create a function, let's call it generateJWT, which takes the user data as input and returns the generated JWT.
2. Encode the user data into a JSON payload. You can use the json_encode() function for this.
3. Create a header array containing the algorithm and token type (typically "JWT"). Encode it into a JSON header.
4. Combine the encoded header and payload with a period (.) in between to create the unsigned token.
5. Create the signature by hashing the unsigned token along with your secret key. You can use the hash_hmac() function with the chosen hashing algorithm (e.g., sha256).
6. Append the signature to the unsigned token with another period (.) to create the complete JWT.
7. Return the generated JWT.

Example implementation:


function generateJWT($userData, $secretKey) {
    // Encode the header
    $header = json_encode([
        'alg' => 'HS256',
        'typ' => 'JWT'

    // Encode the payload
    $payload = json_encode($userData);

    // Create the unsigned token
    $unsignedToken = base64_encode($header) . '.' . base64_encode($payload);

    // Create the signature
    $signature = hash_hmac('sha256', $unsignedToken, $secretKey);

    // Create the JWT
    $jwt = $unsignedToken . '.' . $signature;

    return $jwt;

// Usage example
$secretKey = 'your_secret_key';
$userData = [
    'user_id' => 123,
    'username' => 'john.doe'

$jwt = generateJWT($userData, $secretKey);
echo $jwt;


Replace 'your_secret_key' with a secure secret key of your choice, and customize the $userData array with the relevant user data.


Validate JWT on Protected Routes For routes that require authentication, you need to verify the JWT sent by the client.

Follow these steps to validate a JWT:

1. Create a function, let's call it validateJWT, which takes the JWT and the secret key as input and returns a boolean indicating whether the JWT is valid or not.
2. Split the JWT into its three components: header, payload, and signature. You can use the explode() function with a period (.) as the delimiter.
3. Verify the signature by hashing the unsigned token along with the secret key and comparing it with the extracted signature.
4. If the signature is valid, decode the payload from base64 and parse it as JSON to retrieve the user data.
5. Return true if the signature is valid and the decoded payload is not empty, indicating a valid JWT. Otherwise, return false.

Example implementation:


function validateJWT($jwt, $secretKey) {
    // Split the JWT into its components
    $tokenParts = explode('.', $jwt);

    // Extract the header, payload, and signature
    $header = $tokenParts[0];
    $payload = $tokenParts[1];
    $signature = $tokenParts[2];

    // Verify the signature
    $unsignedToken = $header . '.' . $payload;
    $expectedSignature = hash_hmac('sha256', $unsignedToken, $secretKey);
    if ($signature !== $expectedSignature) {
        return false;

    // Decode the payload
    $decodedPayload = json_decode(base64_decode($payload), true);

    // Check if the payload is empty
    if (empty($decodedPayload)) {
        return false;

    return true;

// Usage example
$secretKey = 'your_secret_key';
$jwt = '...'; // The JWT received from the client

if (validateJWT($jwt, $secretKey)) {
    echo 'Valid token';
} else {
    echo 'Invalid token';


Replace 'your_secret_key' with the same secret key used during JWT generation, and provide the actual JWT received from the client.


That's it! You've implemented JWT generation and validation logic in PHP without relying on any external package. Remember to keep your secret key secure and follow best practices for handling JWTs, such as setting appropriate expiration times and refreshing tokens when necessary.

 More Articles on this Topic: