使用php ping网站

Lou*_*s W 3 php curl ping web

我想创建一个php脚本,它将ping一个域并列出响应时间以及请求的总大小.

这将用于监控网站网络.我尝试过curl,这是我到目前为止的代码:

function curlTest2($url) {
    clearstatcache();

    $return = '';

    if(substr($url,0,4)!="http") $url = "http://".$url;

    $userAgent = 
       'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)';

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 15);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);

    $execute = curl_exec($ch);

    // Check if any error occured
    if(!curl_errno($ch)) {
        $bytes      = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
        $total_time = curl_getinfo($ch, CURLINFO_TOTAL_TIME);
        $return = 'Took ' . $total_time . ' / Bytes: '. $bytes;        
    } else {
        $return = 'Error reaching domain';
    }
    curl_close($ch);

    return $return;

}
Run Code Online (Sandbox Code Playgroud)

这是一个使用fopen

function fopenTest($link) {

    if(substr($link,0,4)!="http"){ 
    $link = "http://".$link;
    }

    $timestart = microtime();

    $churl = @fopen($link,'r');

    $timeend = microtime();
    $diff = number_format(((substr($timeend,0,9)) + (substr($timeend,-10)) - 
        (substr($timestart,0,9)) - (substr($timestart,-10))),4);
    $diff = $diff*100;

    if (!$churl) {
        $message="Offline";
    }else{
        $message="Online. Time : ".$diff."ms ";
    }

    fclose($churl); 

    return  $message;

}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法使用PHP ping网站?

Ste*_*hry 5

显然curl有各种很酷的东西,但请记住,你总是可以通过从命令行调用它们来使用内置工具,如下所示:

$site = "google.com";
ob_start();
system("ping " . escapeshellarg($site));
print ob_end_flush();
Run Code Online (Sandbox Code Playgroud)

唯一要记住的是,这不会像卷曲那样是跨平台的; 虽然默认情况下没有启用curl扩展名.