<?php
/**
* Detects HTTP request errors for a legacy project with a CLI interface.
*
* @param string $url The URL to check.
* @return bool True if the request was successful, false otherwise.
*/
function checkHttpRequest(string $url): bool
{
// Use curl to make the HTTP request
$ch = curl_init($url);
if ($ch === false) {
error_log("curl_init failed for URL: " . $url);
return false; // curl_init failed
}
// Set curl options
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // Return the transfer as a string
curl_setopt($ch, CURLOPT_HEADER, false); // Don't include headers in the output
curl_setopt($ch, CURLOPT_TIMEOUT, 10); // Set a timeout of 10 seconds
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // Disable SSL verification (for testing/legacy)
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // Disable SSL host verification (for testing/legacy)
// Execute the request
$response = curl_exec($ch);
// Check for errors
if ($response === false) {
error_log("curl_exec failed for URL: " . $url . ". Error: " . curl_error($ch));
curl_close($ch);
return false; // curl_exec failed
}
// Get the HTTP status code
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the curl resource
curl_close($ch);
// Check if the status code indicates an error
if ($httpCode >= 400) {
error_log("HTTP error for URL: " . $url . ". Status code: " . $httpCode);
return false; // HTTP error
}
return true; // Success
}
// Example usage (CLI)
if (php_sapi_name() === 'cli') {
if ($argc < 2) {
echo "Usage: php script.php <url>\n";
exit(1);
}
$url = $argv[1];
if (checkHttpRequest($url)) {
echo "Request to $url successful.\n";
} else {
echo "Request to $url failed.\n";
}
}
?>
Add your comment