<?php
/**
* Extends HTTP request handling for local utility with backward compatibility.
*
* This code provides a wrapper around the standard `$_SERVER` variables
* to ensure compatibility with older PHP versions that may not have
* the same request information readily available.
*/
if (!function_exists('get_http_request_info')) {
/**
* Retrieves HTTP request information, handling older PHP versions.
*
* @return array An associative array containing HTTP request details.
*/
function get_http_request_info() {
$request_info = [];
// Check for common request variables. Prioritize newer methods.
$request_info['method'] = $_SERVER['REQUEST_METHOD'] ?? $_SERVER['HTTP_X_HTTP_METHOD'] ?? 'GET';
$request_info['protocol'] = $_SERVER['HTTP_SCHEMA'] ?? 'http'; // or https
$request_info['url'] = $_SERVER['REQUEST_URI'];
$request_info['query'] = $_SERVER['QUERY_STRING'];
$request_info['headers'] = $_SERVER['HTTP_HEADER'] ?? [];
// Handle older versions that might not have all variables.
if (!isset($_SERVER['HTTP_HOST'])) {
$request_info['host'] = $_SERVER['SERVER_NAME'];
} else {
$request_info['host'] = $_SERVER['HTTP_HOST'];
}
if (!isset($_SERVER['SCRIPT_NAME'])) {
$request_info['script_name'] = $_SERVER['PHP_SELF'];
} else {
$request_info['script_name'] = $_SERVER['SCRIPT_NAME'];
}
//Add any custom headers from the X-HTTP_METHOD variable for backwards compatibility.
if (isset($_SERVER['HTTP_X_HTTP_METHOD'])) {
$request_info['x_http_method'] = $_SERVER['HTTP_X_HTTP_METHOD'];
}
return $request_info;
}
}
//Example usage (can be used in your utility script)
// $request_info = get_http_request_info();
// echo "Method: " . $request_info['method'] . "\n";
// echo "URL: " . $request_info['url'] . "\n";
// echo "Host: " . $request_info['host'] . "\n";
// echo "Query: " . $request_info['query'] . "\n";
?>
Add your comment