1. <?php
  2. /**
  3. * Collects metadata metrics with graceful failure handling.
  4. *
  5. * @param string $url The URL to analyze.
  6. * @return array|null An array of metadata metrics, or null on failure.
  7. */
  8. function collectMetadata(string $url): ?array
  9. {
  10. try {
  11. // Initialize an empty array to store metadata metrics.
  12. $metadata = [];
  13. // Use cURL to fetch the URL.
  14. $ch = curl_init($url);
  15. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the result as a string.
  16. curl_setopt($ch, CURLOPT_HEADER, true); // Include headers.
  17. curl_setopt($ch, CURLOPT_NOBODY, true); // Only fetch headers.
  18. $response = curl_exec($ch);
  19. if ($response === false) {
  20. error_log("cURL error: " . curl_error($ch)); // Log cURL errors.
  21. curl_close($ch);
  22. return null; // Return null on cURL failure.
  23. }
  24. curl_close($ch);
  25. // Check if the request was successful (HTTP status code 200).
  26. if (curl_getinfo($ch, CURLINFO_HTTP_CODE) != 200) {
  27. error_log("HTTP error: " . curl_getinfo($ch, CURLINFO_HTTP_CODE)); // Log HTTP errors.
  28. return null; // Return null on HTTP error.
  29. }
  30. // Decode the headers.
  31. $headers = get_headers($url);
  32. if ($headers === false) {
  33. error_log("Failed to get headers for " . $url);
  34. return null;
  35. }
  36. // Extract metadata from the headers.
  37. if (count($headers) > 0) {
  38. $metadata['content_type'] = $headers[0][0]; // Content type.
  39. $metadata['server'] = $headers[0][1]; // Server.
  40. $metadata['date'] = $headers[0][2]; // Date.
  41. } else {
  42. error_log("No headers found for " . $url);
  43. return null;
  44. }
  45. // Example: Extract the size
  46. $metadata['size'] = curl_getinfo($ch, CURLINFO_CONTENT_SIZE);
  47. return $metadata;
  48. } catch (Exception $e) {
  49. error_log("Exception: " . $e->getMessage()); // Log exceptions.
  50. return null; // Return null on exception.
  51. }
  52. }
  53. // Example usage:
  54. $url = 'https://www.example.com';
  55. $metrics = collectMetadata($url);
  56. if ($metrics !== null) {
  57. print_r($metrics); // Output the collected metrics.
  58. } else {
  59. echo "Failed to collect metadata for " . $url . "\n"; // Indicate failure.
  60. }
  61. ?>

Add your comment