Ping站点并在PHP中返回结果

时间:2009-08-06 14:01:00

标签: php ping

我想创建一个小的IF程序来检查Twitter是否可用(例如,与现在不同),并返回true或false。

帮助:)

7 个答案:

答案 0 :(得分:37)

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}  

this post抓取了关于如何检查网址是否存在的问题。

,因为Twitter在维护时应该提供300以上的错误消息,或者404,这应该是完美的。

答案 1 :(得分:21)

这是一个:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?lngWId=8&txtCodeId=1786

另:

function ping($host, $port, $timeout) { 
  $tB = microtime(true); 
  $fP = fSockOpen($host, $port, $errno, $errstr, $timeout); 
  if (!$fP) { return "down"; } 
  $tA = microtime(true); 
  return round((($tA - $tB) * 1000), 0)." ms"; 
}

//Echoing it will display the ping if the host is up, if not it'll say "down".
echo ping("www.google.com", 80, 10);  

答案 2 :(得分:9)

使用shell_exec

<?php
$output = shell_exec('ping -c1 google.com');
echo "<pre>$output</pre>";
?>

答案 3 :(得分:6)

另一个选项(如果您需要/想要ping而不是发送HTTP请求)是Ping class for PHP。我为此目的编写了它,它允许您使用三种支持的方法之一来ping服务器(某些服务器/环境仅支持三种方法中的一种)。

使用示例:

require_once('Ping/Ping.php');
$host = 'www.example.com';
$ping = new Ping($host);
$latency = $ping->ping();
if ($latency) {
  print 'Latency is ' . $latency . ' ms';
}
else {
  print 'Host could not be reached.';
}

答案 4 :(得分:5)

ping几乎适用于所有操作系统。所以你可以进行系统调用并获取结果。

答案 5 :(得分:0)

使用以下功能,您只需使用socket_create发送纯ICMP数据包。我从a user note那里得到了以下代码。注:您必须以 root 运行以下内容。

虽然您无法将其置于标准网页中,但您可以将其作为cron作业运行,并使用结果填充数据库。

因此,如果您需要监控网站,那么它最适合。

function twitterIsUp() {
    return ping('twitter.com');
}

function ping ($host, $timeout = 1) {
    /* ICMP ping packet with a pre-calculated checksum */
    $package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
    $socket = socket_create(AF_INET, SOCK_RAW, 1);
    socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
    socket_connect($socket, $host, null);

    $ts = microtime(true);
    socket_send($socket, $package, strLen($package), 0);
    if (socket_read($socket, 255)) {    
        $result = microtime(true) - $ts;
    } else {
        $result = false;
    }
    socket_close($socket);

    return $result;
}

答案 6 :(得分:0)

这是我用过的php代码,回复通常是这样的:

    2 packets transmitted, 2 received, 0% packet loss, time 1089ms

所以我使用了这样的代码:

  

    $ping_how_many = 2;
    $ping_result = shell_exec('ping -c '.$ping_how_many.' bing.com');
    if( !preg_match('/'.$ping_how_many.' received/',$ping_result) ){
       echo 'Bad ping result'. PHP_EOL;
        // goto next1;
    }