Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🔴 Advanced  ·  Lesson 38

JWT Authentication in PHP

In this lesson: How JWT works and how to build token-based login in PHP — create, sign, verify and expire tokens with example code.

What is JWT

JWT (JSON Web Token) is a way to handle login for APIs. After a user logs in, the server creates a signed token and gives it to the client. The client sends this token with every future request to prove who it is — so the server does not need to store a session for each user.

💡 A JWT is signed, not encrypted. It proves the data was not changed, but anyone can read what is inside.

The three parts of a token

A JWT looks like xxxxx.yyyyy.zzzzz — three parts split by dots.

PartHolds
HeaderThe signing algorithm (e.g. HS256)
PayloadThe data — like user id and expiry
SignatureA check that the token was not tampered with

The header and payload are just base64-encoded (readable), while the signature uses a secret key only the server knows.

How JWT login works

  1. The user logs in with email and password.
  2. The server checks them and, if correct, creates a signed JWT.
  3. The client stores the token and sends it in the header of each request.
  4. The server verifies the signature and reads the user id from the token.
  5. No server-side session is needed — the token carries the proof.

Using a JWT library

Do not build JWTs by hand — use a trusted library like firebase/php-jwt.

<?php
  use Firebase\JWT\JWT;

  $key = "your-secret-key";
  $payload = ["user_id" => 5, "exp" => time() + 3600];
  $token = JWT::encode($payload, $key, "HS256");
  echo $token;   // xxxxx.yyyyy.zzzzz
?>

JWT::encode signs the payload with your secret key. The exp field sets an expiry (here one hour), after which the token is no longer valid.

Verifying a token

<?php
  use Firebase\JWT\JWT;
  use Firebase\JWT\Key;

  try {
      $decoded = JWT::decode($token, new Key($key, "HS256"));
      echo "User id: " . $decoded->user_id;
  } catch (Exception $e) {
      echo "Invalid or expired token";
  }
?>
User id: 5

On each protected request, decode and verify the token. If the signature is wrong or it has expired, decoding throws an error and you reject the request.

Common mistakes

  • Putting secrets in the payload. It is readable — never store passwords or sensitive data there.
  • Writing your own JWT code. Use a tested library to avoid forgeable tokens.
  • No expiry. Always set exp so old tokens stop working.
  • Weak or exposed secret key. Keep the key strong and out of your code repository.

Summary

  • JWT is token-based login, ideal for stateless APIs.
  • A token has three parts: header, payload, signature.
  • It is signed (tamper-proof) but not encrypted (readable).
  • Use a library like firebase/php-jwt to encode and verify.
  • Always set an expiry and keep the secret key safe.

Next, secure the data layer with prepared statements, or compare with sessions and cookies.

Frequently Asked Questions

What is a JWT?
A JWT (JSON Web Token) is a signed string that carries user information. After login, the server gives the client a token; the client sends it back with each request to prove who it is. It is popular for APIs because the server does not need to store sessions.
What are the three parts of a JWT?
A JWT has three parts separated by dots: the header (algorithm info), the payload (the data, like user id), and the signature (a check that the token was not tampered with). They are base64-encoded, not encrypted.
Is the data in a JWT encrypted?
No. The payload is only base64-encoded, so anyone can read it. Never put secrets like passwords in a JWT. The signature only proves the token was not changed, not that its contents are hidden.
Should I write my own JWT code?
No. Use a trusted library like firebase/php-jwt. Signing and verifying tokens correctly is security-critical, and a well-tested library avoids subtle mistakes that could let attackers forge tokens.
What is the difference between JWT and sessions?
Sessions store login state on the server and send a session id in a cookie. JWT stores the signed data on the client and sends the whole token. JWT suits stateless APIs; sessions suit traditional server-rendered sites.
← Back to PHP Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicMVC Architecture Your progress: 38 / 50 (76%) · Lesson 39 / 50 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free