php - How to ping two server address? -
i want have php code ping 2 servers if these servers online php code echo online
this code :
$ip = "ip1"; //ip or web address $port = "22"; //port $ip2 = "ip2"; //ip or web address $port2 = "22"; //port $sock = @fsockopen( $ip, $port, $num, $error, 5 ); //2 ping time, can sub need $sock2 = @fsockopen( $ip2, $port2, $num2, $error2, 5 ); //2 ping time, can sub need if( !$sock & !$sock2 ){ //do if closed echo '<img title="offline" src="../images/down.png">'; } if( $sock & $sock2 ){ //do if open echo '<img title="online" src="../images/up.png">'; fclose($sock); fclose($sock2); } ?>
is correct code ?
your code has few minor issues: if 1 sock open , other not, not close open socket (php close @ end of script anyway), because close them if both open. used binary , (&) instead of logical , && if( $sock && $sock2 ) {
, , ending image tags />
idea make compliant every html flavour.
here multiserver version:
<?php $servers_to_test=array( array( 'ip'=>'192.168.100.1', 'port'=>22, 'timeout'=>5, ), array( 'ip'=>'192.168.100.101', 'port'=>22, 'timeout'=>5, ), ); $all_online=true; $count_online=0; $count_all=count($servers_to_test); foreach($servers_to_test $aserver) { $ip = $aserver['ip']; $port = $aserver['port']; $timeout = $aserver['timeout']; $errnum=0; $errstr=''; $sock = fsockopen( $ip, $port, $errnum, $errstr, $timeout ); if($sock!==false) { fclose($sock1); $count_online++; } else $all_online=false; } if($all_online){ echo '<img alt="all online" title="all online" src="../images/up.png" />'; } else { $perc=($count_all-$count_online).'/'.$count_all; echo '<img alt="offline '.$perc.'" title="offline '.$perc.'" src="../images/down.png" />'; } ?>
if test way many servers, take while, there ways make run tests in parallel webserver (without threads), have make single script test 1 server "seeifonline.php" (the server parameter url) , open script many times nonblocking sockets localhost,80 (they reply immediately) , manually writing 'get seeifonline.php?sever=$server' different $server each one. wait in loop replies. it's complicated works , can check status of 20 servers in same time 1 (5 seconds timeout). main difference know localhost server online, fsockopens localhost reply , launch script. script calls fsockopen 1 remote host, , it hangs till timeout, other scrips go on independent threads.
Comments
Post a Comment