1. <?php
  2. /**
  3. * Attaches metadata to HTTP requests for internal tooling.
  4. *
  5. * @param array $options An associative array of options.
  6. * 'request_id' => Unique identifier for the request.
  7. * 'user_id' => User ID making the request.
  8. * 'custom_data' => Associative array of custom data.
  9. * @return array|false Returns an array of headers to add, or false on error.
  10. */
  11. function attachRequestMetadata(array $options): array|false
  12. {
  13. // Validate options
  14. if (empty($options) || !isset($options['request_id'])) {
  15. error_log("Missing 'request_id' option.");
  16. return false;
  17. }
  18. $request_id = $options['request_id'];
  19. $user_id = isset($options['user_id']) ? $options['user_id'] : 'anonymous'; // Default to anonymous if not provided
  20. $custom_data = isset($options['custom_data']) ? $options['custom_data'] : [];
  21. // Build headers
  22. $headers = [];
  23. // Request ID
  24. $headers[] = 'X-Request-ID: ' . $request_id;
  25. // User ID
  26. $headers[] = 'X-User-ID: ' . $user_id;
  27. // Custom Data
  28. foreach ($custom_data as $key => $value) {
  29. $headers[] = 'X-Custom-' . $key . ': ' . $value;
  30. }
  31. return $headers;
  32. }
  33. /**
  34. * Example usage (replace with your actual framework/application integration)
  35. */
  36. if (PHP_SAPI === 'cli') {
  37. $options = [
  38. 'request_id' => uniqid(),
  39. 'user_id' => '123',
  40. 'custom_data' => [
  41. 'environment' => 'development',
  42. 'version' => '1.0',
  43. ],
  44. ];
  45. $headers = attachRequestMetadata($options);
  46. if ($headers !== false) {
  47. foreach ($headers as $header) {
  48. echo $header . "\n";
  49. }
  50. } else {
  51. echo "Error attaching metadata.\n";
  52. }
  53. }
  54. ?>

Add your comment