How does a PHP script handle authentication with JWT for a REST API?

To handle authentication with JWT for a REST API in PHP, you need to verify the JWT token sent in the request header. This involves decoding the token, checking its validity, and extracting the user information if it's valid. You can then use this user information to authenticate and authorize the user for accessing the API endpoints.

<?php

// Get the JWT token from the request header
$token = $_SERVER['HTTP_AUTHORIZATION'];

// Decode the JWT token
$decoded_token = jwt_decode($token);

// Check if the token is valid
if ($decoded_token) {
    // Extract user information from the token
    $user_id = $decoded_token['user_id'];
    
    // Perform authentication and authorization logic here
    // For example, check if the user has the necessary permissions to access the API endpoint
} else {
    http_response_code(401);
    echo json_encode(array("message" => "Unauthorized"));
}