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

How can I check if RESTAPI is down using curl php

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

案例:如果Web服务关闭7秒,那么系统应该重试一次,如果不工作,那么它应该将通知发送给管理员。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$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);


你可以试试这个:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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();