How to ping an address and return the min, max and average results with PHP on both Windows and Linux.
The reason the operating system matters is because the ping method and output is different depending on the system.
Linux systems use a -c for the ping attempt amounts whilst Windows is -n.
Determining if the webserver is on a Windows operating system or Linux with PHP:
if (stripos(PHP_OS, 'WIN') === 0) {
//Windows OS
} else {
//Linux OS
} The doPing function:
function doPing(string $address): array
{
if (stripos(PHP_OS, 'WIN') === 0) {//Windows OS
exec("ping -n 3 $address", $output, $status);
$values = explode('=', $output[9]);
$min = filter_var($values[1], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$max = filter_var($values[2], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$avg = filter_var($values[3], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
} else {//Linux OS
$output = explode("\n", shell_exec("ping -c 3 $address"));
$values = explode("/", $output[7]);
$min = filter_var($values[3], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$max = filter_var($values[5], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
$avg = filter_var($values[4], FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
}
return array('min' => $min, 'max' => $max, 'avg' => $avg, 'from' => $_SERVER['SERVER_ADDR'], 'to' => $address);
}
Calling the function:
echo json_encode(doPing('8.8.8.8')); The functions process is to split the output and then filter the string to only get the float with filter_var(). Meaning only numbers and decimals are kept.
A drained and empty Kennington reservoir images from a drone in early July 2024. The…
Merrimu Reservoir from drone. Click images to view larger.
Some early September spring shots from a bushwalk, It is still too early for wildflowers.
I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…
If you ever needed a simple solution in Laravel to delete an entire directory and…
How to enforce only one user to register or be registered in a Laravel web…