Categories: Development

Ping address and get min, max & average with PHP

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.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago