1. <?php
  2. /**
  3. * API Endpoint Error Checker (No Async)
  4. *
  5. * This script checks API endpoints for errors and outputs them.
  6. * It does not use asynchronous logic and processes requests sequentially.
  7. */
  8. // Define the API endpoint URLs to check
  9. $endpoints = [
  10. 'https://api.example.com/endpoint1',
  11. 'https://api.example.com/endpoint2',
  12. 'https://api.example.com/endpoint3',
  13. ];
  14. // Function to check an API endpoint
  15. function checkEndpoint($url) {
  16. try {
  17. $response = file_get_contents($url); // Simple HTTP request
  18. if ($response === false) {
  19. return "Error: Could not connect to $url";
  20. }
  21. $status_code = (int)substr($response, 0, 3); // Extract status code from response
  22. $body = $response; // Use the entire response as the body
  23. if ($status_code >= 400) {
  24. // Check for specific error messages in the response body
  25. $error_message = error_log_to_string($body); // Helper function
  26. return "Error: HTTP Status Code $status_code - $error_message";
  27. } else {
  28. return "Success: HTTP Status Code $status_code";
  29. }
  30. } catch (Exception $e) {
  31. return "Error: Exception - " . $e->getMessage();
  32. }
  33. }
  34. /**
  35. * Helper function to extract error message from a response body
  36. *
  37. * @param string $body The response body.
  38. * @return string The error message.
  39. */
  40. function error_log_to_string($body) {
  41. //Basic error checking, can be improved with regex
  42. if (strpos($body, 'error') !== false) {
  43. return trim(substr($body, strpos($body, 'error')));
  44. }
  45. return $body;
  46. }
  47. // Loop through the endpoints and check them
  48. foreach ($endpoints as $endpoint) {
  49. $error = checkEndpoint($endpoint);
  50. echo "Endpoint: $endpoint\n";
  51. echo $error . "\n\n";
  52. }
  53. ?>

Add your comment