1. <?php
  2. /**
  3. * Validates response headers against a configuration with a timeout.
  4. *
  5. * @param array $expectedHeaders Array of expected headers and their values.
  6. * @param int $timeout Timeout in seconds.
  7. * @param string $url The URL to validate.
  8. * @return bool True if all headers are valid, false otherwise.
  9. */
  10. function validateResponseHeaders(array $expectedHeaders, int $timeout, string $url): bool
  11. {
  12. $start = time();
  13. $response = @file_get_contents($url, false, stream_context_create([
  14. 'timeout' => $timeout,
  15. ]));
  16. if ($response === false) {
  17. // Handle timeout or other errors during request
  18. return false;
  19. }
  20. $end = time();
  21. if (($end - $start) > $timeout) {
  22. //Timeout occurred
  23. return false;
  24. }
  25. $headers = get_headers($url);
  26. if ($headers === false) {
  27. return false; //Error getting headers
  28. }
  29. foreach ($expectedHeaders as $headerName => $expectedValue) {
  30. if (isset($headers[0][$headerName])) {
  31. if (strtolower($headers[0][$headerName]) !== strtolower($expectedValue)) {
  32. return false; // Header value does not match
  33. }
  34. } else {
  35. return false; //Expected header is missing
  36. }
  37. }
  38. return true; //All headers are valid
  39. }
  40. // Example Usage:
  41. /*
  42. $expectedHeaders = [
  43. 'Content-Type' => 'application/json',
  44. 'X-Custom-Header' => 'my-value',
  45. ];
  46. $timeout = 5; // seconds
  47. $url = 'https://example.com/api/data';
  48. if (validateResponseHeaders($expectedHeaders, $timeout, $url)) {
  49. echo "Response headers are valid.\n";
  50. } else {
  51. echo "Response headers are invalid.\n";
  52. }
  53. */
  54. ?>

Add your comment