1. <?php
  2. /**
  3. * Archives HTTP response content for testing edge cases.
  4. *
  5. * @param string $url The URL to fetch.
  6. * @param string $archive_dir The directory to save the archive to.
  7. * @return bool True on success, false on failure.
  8. */
  9. function archive_http_response(string $url, string $archive_dir): bool
  10. {
  11. // Validate inputs
  12. if (empty($url) || empty($archive_dir)) {
  13. error_log("Invalid URL or archive directory.");
  14. return false;
  15. }
  16. // Ensure archive directory exists
  17. if (!is_dir($archive_dir)) {
  18. if (!mkdir($archive_dir, 0777, true)) {
  19. error_log("Failed to create archive directory: " . $archive_dir);
  20. return false;
  21. }
  22. }
  23. try {
  24. // Fetch the HTTP response
  25. $response = file_get_contents($url);
  26. if ($response === false) {
  27. error_log("Failed to fetch URL: " . $url);
  28. return false;
  29. }
  30. // Determine filename
  31. $filename = basename($url); // Use URL basename as filename
  32. $filepath = $archive_dir . '/' . $filename;
  33. // Save the response to a file
  34. if (file_put_contents($filepath, $response) === false) {
  35. error_log("Failed to save response to file: " . $filepath);
  36. return false;
  37. }
  38. return true;
  39. } catch (Exception $e) {
  40. error_log("Exception: " . $e->getMessage());
  41. return false;
  42. }
  43. }
  44. // Example usage (can be removed)
  45. /*
  46. $url = 'https://www.example.com';
  47. $archive_dir = 'response_archives';
  48. if (archive_http_response($url, $archive_dir)) {
  49. echo "Successfully archived content from $url to $archive_dir\n";
  50. } else {
  51. echo "Failed to archive content from $url\n";
  52. }
  53. */
  54. ?>

Add your comment