代码之家  ›  专栏  ›  技术社区  ›  Louis W

使用PHP ping网站

  •  3
  • Louis W  · 技术社区  · 16 年前

    我想创建一个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;
    
    }
    

    这里有一个用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;
    
    }
    

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

    7 回复  |  直到 13 年前
        1
  •  0
  •   txwikinger    16 年前

    可以使用xmlrpc( xmlrpc_client )不知道卷曲的优点/缺点是什么。

    Drupal为此使用了xmlrpc(查看ping模块)。

        2
  •  5
  •   Andrew Moore    16 年前

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

    $site = "google.com";
    ob_start();
    system("ping " . escapeshellarg($site));
    print ob_end_flush();
    

    唯一要记住的是,这不会像curl那样跨平台;尽管默认情况下也不启用curl扩展。

        3
  •  2
  •   niteria    16 年前

    当为一次性任务执行快速脚本时,我只执行()wget:

    $response = `wget http://google.com -O -`;
    

    它很简单,并且负责重定向。

    如果使用suhosin补丁和curl,可能会遇到HTTP重定向问题(301、302…), 苏霍辛不允许。

        4
  •  1
  •   Ahmet Kakıcı    16 年前

    我对卷发不太确定,但是 this Benchmark说文件获取内容比fopen有更好的性能。

        5
  •  0
  •   Dave Archer    16 年前

    使用卷发很好。

    但不确定是否使用该useragent字符串。除非你特别需要,还是做一个定制的吧。

        6
  •  0
  •   damko    16 年前

    也许这个梨 Net_Ping 就是你要找的。它不再被维护,但它起作用了。

        7
  •  0
  •   ceejayoz    16 年前

    如果启用了远程fopen, file_get_contents() 也会成功的。