Ping站点并在PHP中返回结果

Tom*_*ash 25 php ping

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

救命 :)

Tyl*_*ter 41

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;  
    }  
}  
Run Code Online (Sandbox Code Playgroud)

这是从抓住这个职位上如何检查是否存在URL.因为Twitter应该在维护时提供300以上的错误消息,或者404,这应该是完美的.


kar*_*m79 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);  
Run Code Online (Sandbox Code Playgroud)

  • 这没有好的回报价值.为什么不在失败时返回0/false/null,并且一个整数表示成功时的毫秒数? (8认同)
  • Ping正在研究ICMP协议,没有像'port'这样的东西.您可以使用0个打开的tcp端口ping主机. (4认同)
  • @Philippe Gerber - 因为我没有写,但这些都是很好的建议. (2认同)

Elz*_*ugi 9

使用shell_exec:

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

  • 您应该在Linux上使用`ping -c1 host`或其他东西.普通的"ping主机"不会返回那里. (4认同)

gee*_*guy 6

另一个选项(如果您需要/想要ping而不是发送HTTP请求)是PHPPing类.我为此目的编写了它,它允许您使用三种支持的方法之一来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.';
}
Run Code Online (Sandbox Code Playgroud)


Phi*_*ber 5

ping几乎每个操作系统都可用.所以你可以进行系统调用并获取结果.