1. <?php
  2. /**
  3. * Splits request headers for diagnostics with a timeout.
  4. *
  5. * @param array $headers The request headers array.
  6. * @param int $timeout The timeout in seconds.
  7. * @return array|null An array of diagnostic header data, or null on timeout.
  8. */
  9. function getDiagnosticHeaders(array $headers, int $timeout): ?array
  10. {
  11. $startTime = time();
  12. $diagnosticData = [];
  13. // Iterate through headers
  14. foreach ($headers as $header => $value) {
  15. // Check for timeout
  16. if (time() - $startTime > $timeout) {
  17. return null; // Timeout
  18. }
  19. // Add header to diagnostic data
  20. $diagnosticData[$header] = $value;
  21. }
  22. return $diagnosticData;
  23. }
  24. //Example usage:
  25. // Simulate request headers
  26. $headers = [
  27. 'Content-Type' => 'application/json',
  28. 'Authorization' => 'Bearer my_token',
  29. 'X-Request-ID' => '12345',
  30. 'Accept' => 'application/json',
  31. 'User-Agent' => 'My App/1.0'
  32. ];
  33. // Set timeout
  34. $timeout = 2; //seconds
  35. // Get diagnostic headers
  36. $diagnosticHeaders = getDiagnosticHeaders($headers, $timeout);
  37. if ($diagnosticHeaders !== null) {
  38. // Output the diagnostic headers (for demonstration)
  39. echo "<pre>";
  40. print_r($diagnosticHeaders);
  41. echo "</pre>";
  42. } else {
  43. echo "Request timed out.";
  44. }
  45. ?>

Add your comment