【问题标题】:PHP Ping script error 500PHP Ping 脚本错误 500
【发布时间】:2017-12-22 15:26:52
【问题描述】:

脚本正在运行,但如果主机我尝试 ping 不应答或请求超时,我从服务器收到错误 500。

如果可能的话,我想在我的 php 代码中解决这个问题。

我想要的是,如果主机在 ping 上超时,那么只需显示“超时”而不是来自服务器的错误。

    <html>
        <head>
        <meta http-equiv="refresh" content="30" >
<?php
error_reporting(0); // Turn off all error reporting
?>
        </head>
        <body bgcolor="#222222">
        <center>
        <table width="100%" height="" border="1" cellpadding="3" style="color:black">
        <tr>     



<td align = center width="150"
<?php
function icmp_checksum($data) {
  if (strlen($data) % 2) {
    $data .= "\x00";
  }
  $bit = unpack('n*', $data);
  $sum = array_sum($bit);
  while  ($sum  >> 16) {
    $sum = ($sum >> 16) + ($sum & 0xffff);
  }
  return pack('n*', ~$sum);
}
function ping($host) {

  $tmp = "\x08\x00\x00\x00\x00\x00\x00\x00PingTest";
  $checksum = icmp_checksum($tmp);
  $package = "\x08\x00".$checksum."\x00\x00\x00\x00PingTest";
  $socket = socket_create(AF_INET, SOCK_RAW, 1);
  socket_connect($socket, $host, null);
  $timer = microtime(1);
  socket_send($socket, $package, strlen($package), 0);
  if (socket_read($socket, 255)) {
    return round((microtime(1) - $timer) * 1000, 2);
  }
}

$host="telia.se";
$pingtime = ping ($host);

if ($pingtime == FALSE) 
    echo "bgcolor='red" ."' >"; 
else if ($pingtime > 40) 
    echo "bgcolor='yellow" ."' >"; 
else 
    echo "bgcolor='lime" ."' >";
echo ("<h2><B>$host</b></h2>");
echo $pingtime."ms";
?>
</td>

            </tr>
            </table>
            </center>
            </body>

    </html>

【问题讨论】:

  • 您的具体错误是什么?
  • 错误 500 内部服务器错误

标签: php timeout ping


【解决方案1】:

只有在 ping 成功时,您的函数才会返回一个值。更新它以在失败时返回一个值:

if (socket_read($socket, 255)) {
    return round((microtime(1) - $timer) * 1000, 2);
} else {
    return false;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-08
    • 1970-01-01
    • 2015-08-15
    • 2016-05-08
    相关资源
    最近更新 更多