<?php
/**
* Instruments response headers for a one-off script with fixed retry intervals.
*
* @param string $url The URL to fetch.
* @param int $maxRetries The maximum number of retries.
* @param int $retryInterval The interval between retries in seconds.
* @return array|false An associative array of response headers on success, or false on failure.
*/
function instrumentResponseHeaders(string $url, int $maxRetries, int $retryInterval): array|false
{
$retries = 0;
while ($retries < $maxRetries) {
try {
// Attempt to fetch the URL.
$response = file_get_contents($url);
if ($response === false) {
// Handle failure to fetch the URL.
$retries++;
if ($retries < $maxRetries) {
sleep($retryInterval);
} else {
return false; // Return false if max retries reached.
}
continue;
}
// Initialize headers array.
$headers = [];
// Add the Content-Type header (example).
if (isset($headers['Content-Type'])) {
$headers['Content-Type'] = 'Content-Type: ' . substr($response, 0, strpos($response, "\r\n")); // Get content type
}
// Add other headers as needed. Can use regular expressions to parse.
// Example: Add a custom header.
$headers['X-Instrumented'] = 'true';
// Return the headers.
return $headers;
} catch (Exception $e) {
// Handle exceptions.
$retries++;
if ($retries < $maxRetries) {
sleep($retryInterval);
} else {
return false; // Return false if max retries reached.
}
continue;
}
}
return false; // Should not reach here, but added for completeness.
}
// Example usage (replace with your actual URL, max retries, and interval).
//$url = 'https://www.example.com';
//$maxRetries = 3;
//$retryInterval = 5;
//$headers = instrumentResponseHeaders($url, $maxRetries, $retryInterval);
//if ($headers !== false) {
// // Process the headers.
// print_r($headers);
//} else {
// echo "Failed to retrieve response headers after multiple retries.\n";
//}
?>
Add your comment