1. <?php
  2. /**
  3. * Extends HTTP request handling for local utility with backward compatibility.
  4. *
  5. * This code provides a wrapper around the standard `$_SERVER` variables
  6. * to ensure compatibility with older PHP versions that may not have
  7. * the same request information readily available.
  8. */
  9. if (!function_exists('get_http_request_info')) {
  10. /**
  11. * Retrieves HTTP request information, handling older PHP versions.
  12. *
  13. * @return array An associative array containing HTTP request details.
  14. */
  15. function get_http_request_info() {
  16. $request_info = [];
  17. // Check for common request variables. Prioritize newer methods.
  18. $request_info['method'] = $_SERVER['REQUEST_METHOD'] ?? $_SERVER['HTTP_X_HTTP_METHOD'] ?? 'GET';
  19. $request_info['protocol'] = $_SERVER['HTTP_SCHEMA'] ?? 'http'; // or https
  20. $request_info['url'] = $_SERVER['REQUEST_URI'];
  21. $request_info['query'] = $_SERVER['QUERY_STRING'];
  22. $request_info['headers'] = $_SERVER['HTTP_HEADER'] ?? [];
  23. // Handle older versions that might not have all variables.
  24. if (!isset($_SERVER['HTTP_HOST'])) {
  25. $request_info['host'] = $_SERVER['SERVER_NAME'];
  26. } else {
  27. $request_info['host'] = $_SERVER['HTTP_HOST'];
  28. }
  29. if (!isset($_SERVER['SCRIPT_NAME'])) {
  30. $request_info['script_name'] = $_SERVER['PHP_SELF'];
  31. } else {
  32. $request_info['script_name'] = $_SERVER['SCRIPT_NAME'];
  33. }
  34. //Add any custom headers from the X-HTTP_METHOD variable for backwards compatibility.
  35. if (isset($_SERVER['HTTP_X_HTTP_METHOD'])) {
  36. $request_info['x_http_method'] = $_SERVER['HTTP_X_HTTP_METHOD'];
  37. }
  38. return $request_info;
  39. }
  40. }
  41. //Example usage (can be used in your utility script)
  42. // $request_info = get_http_request_info();
  43. // echo "Method: " . $request_info['method'] . "\n";
  44. // echo "URL: " . $request_info['url'] . "\n";
  45. // echo "Host: " . $request_info['host'] . "\n";
  46. // echo "Query: " . $request_info['query'] . "\n";
  47. ?>

Add your comment