1. <?php
  2. /**
  3. * Detects HTTP request errors for a legacy project with a CLI interface.
  4. *
  5. * @param string $url The URL to check.
  6. * @return bool True if the request was successful, false otherwise.
  7. */
  8. function checkHttpRequest(string $url): bool
  9. {
  10. // Use curl to make the HTTP request
  11. $ch = curl_init($url);
  12. if ($ch === false) {
  13. error_log("curl_init failed for URL: " . $url);
  14. return false; // curl_init failed
  15. }
  16. // Set curl options
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string
  18. curl_setopt($ch, CURLOPT_HEADER, false); // Don't include headers in the output
  19. curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Set a timeout of 10 seconds
  20. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification (for testing/legacy)
  21. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Disable SSL host verification (for testing/legacy)
  22. // Execute the request
  23. $response = curl_exec($ch);
  24. // Check for errors
  25. if ($response === false) {
  26. error_log("curl_exec failed for URL: " . $url . ". Error: " . curl_error($ch));
  27. curl_close($ch);
  28. return false; // curl_exec failed
  29. }
  30. // Get the HTTP status code
  31. $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  32. // Close the curl resource
  33. curl_close($ch);
  34. // Check if the status code indicates an error
  35. if ($httpCode >= 400) {
  36. error_log("HTTP error for URL: " . $url . ". Status code: " . $httpCode);
  37. return false; // HTTP error
  38. }
  39. return true; // Success
  40. }
  41. // Example usage (CLI)
  42. if (php_sapi_name() === 'cli') {
  43. if ($argc < 2) {
  44. echo "Usage: php script.php <url>\n";
  45. exit(1);
  46. }
  47. $url = $argv[1];
  48. if (checkHttpRequest($url)) {
  49. echo "Request to $url successful.\n";
  50. } else {
  51. echo "Request to $url failed.\n";
  52. }
  53. }
  54. ?>

Add your comment