I have been using the script below, however, I want it to ping 3-4 times, and within that 3-4 times if it has even a single request timeout, I want php to come back as failed.
Here's a script I'm using:
<?php
function pingAddressHasNeverFailed($tries) {
for ($i = 0; $i < $tries; $i++) {
$pingresult = shell_exec("ping -c 1 www.google.com", $outcome, $status);
if ($status != 0)
return false;
}
return true;
}
if (pingAddressHasNeverFailed(3)) {
echo "uoc gi";
}
?>
Please help if you can, thank you so much in advance!
If any ping fails (in a set) it will not have 0%
in the output (i.e. 0%
packet loss), which is the same for Linux and Windows:
function ping($host, $times = 3)
{
exec("/bin/ping -c 3 $host", $out, $status);
return $status === 0 && false !== strpos(join('', $out), '0%');
}
if (ping('www.google.com)) {
echo "yay
";
} else {
echo "oh dear
";
}
You may have to adjust the ping
arguments to fit your environment and make sure that the host name is sanitized.
In that case you'll need to execute command n (n is a number of tries) times. E.g.:
function pingAddressHasNeverFailed($tries) {
$outcome = array();
$status = -1;
for ($i = 0; $i < $tries; $i++) {
$pingresult = exec("/bin/ping -n 1 www.google.com", $outcome, $status);
if ($status != 0)
return false;
}
return true;
}
Usage:
if (pingAddressHasNeverFailed(3)) {
//do something useful
}