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…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago