<?php
/**
* Archives HTTP response content for testing edge cases.
*
* @param string $url The URL to fetch.
* @param string $archive_dir The directory to save the archive to.
* @return bool True on success, false on failure.
*/
function archive_http_response(string $url, string $archive_dir): bool
{
// Validate inputs
if (empty($url) || empty($archive_dir)) {
error_log("Invalid URL or archive directory.");
return false;
}
// Ensure archive directory exists
if (!is_dir($archive_dir)) {
if (!mkdir($archive_dir, 0777, true)) {
error_log("Failed to create archive directory: " . $archive_dir);
return false;
}
}
try {
// Fetch the HTTP response
$response = file_get_contents($url);
if ($response === false) {
error_log("Failed to fetch URL: " . $url);
return false;
}
// Determine filename
$filename = basename($url); // Use URL basename as filename
$filepath = $archive_dir . '/' . $filename;
// Save the response to a file
if (file_put_contents($filepath, $response) === false) {
error_log("Failed to save response to file: " . $filepath);
return false;
}
return true;
} catch (Exception $e) {
error_log("Exception: " . $e->getMessage());
return false;
}
}
// Example usage (can be removed)
/*
$url = 'https://www.example.com';
$archive_dir = 'response_archives';
if (archive_http_response($url, $archive_dir)) {
echo "Successfully archived content from $url to $archive_dir\n";
} else {
echo "Failed to archive content from $url\n";
}
*/
?>
Add your comment