如何使用curl php检查RESTAPI是否已关闭

时间:2018-04-30 08:18:07

标签: php curl

我想创建一个虚拟环境来检查Web服务是否已关闭。

案例:如果网络服务停机7秒钟,那么系统应重新尝试一次,如果不能正常工作,则应将通知发送给管理员。


    $ch = curl_init();
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_URL, $url); 
    // Use 0 to wait indefinitely.
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 7);
    // The maximum number of seconds to allow cURL functions to execute
    curl_setopt($ch, CURLOPT_TIMEOUT, 7);
    curl_setopt($ch, CURLOPT_HEADER, FALSE); 
    //curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $responseData = curl_exec($ch); 

    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    $httpCode = curl_getinfo($ch); 
    curl_close($ch);

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

$url = 'my.url';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($retcode == 200)
{
    // It's working
}
else
{
    // It's down
}

答案 1 :(得分:0)

最后,我找到了解决方案。

function checkData($loop = 0){
    $url = 'http://google.co.in:8080/';
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_FAILONERROR, true);
    curl_setopt($ch, CURLOPT_URL, $url); 
    // Use 0 to wait indefinitely.
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 7);
    // The maximum number of seconds to allow cURL functions to execute
    curl_setopt($ch, CURLOPT_TIMEOUT, 7);
    curl_setopt($ch, CURLOPT_HEADER, FALSE); 
    //curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    $responseData = curl_exec($ch); 

    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    $httpCode = curl_getinfo($ch); 
    curl_close($ch);

    if ($curl_errno > 0){
        if($loop > 1 ){
           //send mail to admin
        }else{
           $loop++;
           sleep(7);
           checkData();
        }
    }
}
checkData();