1. <?php
  2. /**
  3. * Instruments response headers for a one-off script with fixed retry intervals.
  4. *
  5. * @param string $url The URL to fetch.
  6. * @param int $maxRetries The maximum number of retries.
  7. * @param int $retryInterval The interval between retries in seconds.
  8. * @return array|false An associative array of response headers on success, or false on failure.
  9. */
  10. function instrumentResponseHeaders(string $url, int $maxRetries, int $retryInterval): array|false
  11. {
  12. $retries = 0;
  13. while ($retries < $maxRetries) {
  14. try {
  15. // Attempt to fetch the URL.
  16. $response = file_get_contents($url);
  17. if ($response === false) {
  18. // Handle failure to fetch the URL.
  19. $retries++;
  20. if ($retries < $maxRetries) {
  21. sleep($retryInterval);
  22. } else {
  23. return false; // Return false if max retries reached.
  24. }
  25. continue;
  26. }
  27. // Initialize headers array.
  28. $headers = [];
  29. // Add the Content-Type header (example).
  30. if (isset($headers['Content-Type'])) {
  31. $headers['Content-Type'] = 'Content-Type: ' . substr($response, 0, strpos($response, "\r\n")); // Get content type
  32. }
  33. // Add other headers as needed. Can use regular expressions to parse.
  34. // Example: Add a custom header.
  35. $headers['X-Instrumented'] = 'true';
  36. // Return the headers.
  37. return $headers;
  38. } catch (Exception $e) {
  39. // Handle exceptions.
  40. $retries++;
  41. if ($retries < $maxRetries) {
  42. sleep($retryInterval);
  43. } else {
  44. return false; // Return false if max retries reached.
  45. }
  46. continue;
  47. }
  48. }
  49. return false; // Should not reach here, but added for completeness.
  50. }
  51. // Example usage (replace with your actual URL, max retries, and interval).
  52. //$url = 'https://www.example.com';
  53. //$maxRetries = 3;
  54. //$retryInterval = 5;
  55. //$headers = instrumentResponseHeaders($url, $maxRetries, $retryInterval);
  56. //if ($headers !== false) {
  57. // // Process the headers.
  58. // print_r($headers);
  59. //} else {
  60. // echo "Failed to retrieve response headers after multiple retries.\n";
  61. //}
  62. ?>

Add your comment