Fix for Undefined Index: Authorization Error
The "Undefined index: Authorization" error in PHP usually means you're trying to access the
$_SERVER['Authorization']
superglobal variable, but it's not set. This variable is used to retrieve the Authorization header sent by the client, often in authentication scenarios (like Bearer tokens, Basic Auth, etc.).Check if the Header is Sent:
- Problem: The client might not be sending the
Authorization
header at all. - Solution: Use
isset()
to check if the header exists before trying to access it:
LET SUPPOSE :Notice: Undefined index: Authorization in on line 27 in PHP
This means the Authorization
header is missing from the request.
Fix
Modify your script to check if the Authorization header is set before accessing it:
// Get headers and validate Authorization token
$headers = apache_request_headers();
if (!isset($headers['Authorization'])) {
die(json_encode(["status" => 401, "message" => "Token not provided"]));
}
$jwt = str_replace("Bearer ", "", $headers['Authorization']);
Full Code-
<?phpinclude_once($_SERVER['DOCUMENT_ROOT'] . "/cmms/utils/header.php");require __DIR__ . '/../vendor/autoload.php';use \Firebase\JWT\JWT;use \Firebase\JWT\Key;// Enable error reporting for debuggingini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL);// Ensure the connection variable is definedif (!isset($conn)) {die(json_encode(["status" => 500, "message" => "Database connection is not defined."]));}// Get headers and validate Authorization token$headers = apache_request_headers();if (!isset($headers['Authorization'])) {die(json_encode(["status" => 401, "message" => "Token not provided"]));}$jwt = str_replace("Bearer ", "", $headers['Authorization']);$FOR_DATE = $_REQUEST['FOR_DATE'] ?? null;$EMPNO = $_REQUEST['EMPNO'] ?? null;try {// Decode the JWT token// Decode the JWT token$decoded = JWT::decode($jwt, new \Firebase\JWT\Key($secret_key, 'HS256'));// Execute database query$sql = oci_parse($conn, "select ^from Table name'");if (!$sql) {throw new Exception("Failed to prepare the SQL statement.");}$executionResult = oci_execute($sql);if (!$executionResult) {$error = oci_error($sql);throw new Exception("Database execution error: " . $error['message']);}$rows = [];while ($r = oci_fetch_assoc($sql)) {$rows[] = array_map('htmlentities', $r);}// Return responseecho json_encode(["status" => 200,"message" => "Access granted","data" => ["jwtData" => $decoded,"databaseResult" => $rows]]);} catch (\Firebase\JWT\ExpiredException $e) {echo json_encode(["status" => 401, "message" => "Token expired", "error" => $e->getMessage()]);// Return response} catch (\Firebase\JWT\SignatureInvalidException $e) {echo json_encode(["status" => 401, "message" => "Invalid signature", "error" => $e->getMessage()]);} catch (Exception $e) {echo json_encode(["status" => 500, "message" => "Internal Server Error", "error" => $e->getMessage()]);}?>
Possible Reasons for Missing Authorization Header
Client is not sending the token properly
- Ensure the request includes the
Authorization
header, Apache is stripping Authorization headers
Running on Nginx or PHP-FPM
Final Thoughts
✅ Fix ensures the script does not throw undefined index error.
✅ Works across different servers that might modify header case.
✅ Ensures Authorization
is always validated before use. 🚀
Post a Comment
0Comments