How to Execute and Parse Ping Results in PHP for Structured Network Diagnostics

Learn how to run the ping command from PHP, format its raw output, parse statistics into a structured array, handle cross‑platform differences, ensure security with input validation, and display results in a user‑friendly HTML format for robust network diagnostics.

php Courses
php Courses
php Courses
How to Execute and Parse Ping Results in PHP for Structured Network Diagnostics

In web development and system administration, the ping command is a common network diagnostic tool for testing connectivity between hosts. PHP, a popular server‑side scripting language, can execute system commands and output the results in a structured way.

Basic Ping command execution

PHP provides several functions to run system commands, the most common being exec(), shell_exec() and system(). The following example uses shell_exec() to run a ping:

<code><?php
$host = 'example.com';
$pingResult = shell_exec("ping -c 4 {$host}");
echo "<pre>{$pingResult}

"; ?>

This code sends four ping packets to example.com and prints the raw result in the browser.

Structured output of ping results

To make the ping output easier to read and analyze, we can parse it into a structured array:

<code><?php
function structuredPing($host, $count = 4) {
    $command = "ping -c {$count} {$host}";
    $output = shell_exec($command);
    if (empty($output)) {
        return ['error' => 'Ping command failed or host is unreachable'];
    }
    // Parse output
    $lines = explode("
", $output);
    $result = [
        'host' => $host,
        'packets_transmitted' => 0,
        'packets_received' => 0,
        'packet_loss' => 0,
        'round_trip' => [],
        'details' => []
    ];
    foreach ($lines as $line) {
        // Statistics line
        if (preg_match('/(\d+) packets transmitted, (\d+) received, (\d+)% packet loss/', $line, $matches)) {
            $result['packets_transmitted'] = $matches[1];
            $result['packets_received'] = $matches[2];
            $result['packet_loss'] = $matches[3];
        }
        // Round‑trip times
        if (preg_match('/rtt min\/avg\/max\/mdev = ([\d.]+)\/([\d.]+)\/([\d.]+)\/([\d.]+) ms/', $line, $matches)) {
            $result['round_trip'] = [
                'min' => $matches[1],
                'avg' => $matches[2],
                'max' => $matches[3],
                'mdev' => $matches[4]
            ];
        }
        // Per‑packet details
        if (preg_match('/icmp_seq=(\d+) ttl=(\d+) time=([\d.]+) ms/', $line, $matches)) {
            $result['details'][] = [
                'sequence' => $matches[1],
                'ttl' => $matches[2],
                'time' => $matches[3]
            ];
        }
    }
    return $result;
}
$pingData = structuredPing('google.com');
echo '<pre>' . print_r($pingData, true) . '

'; ?>

Cross‑platform compatibility handling

Different operating systems use different ping parameters (Windows uses -n, Linux/Unix uses -c). The following function detects the OS and builds the appropriate command:

<code><?php
function osAwarePing($host, $count = 4) {
    if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
        $command = "ping -n {$count} {$host}";
    } else {
        $command = "ping -c {$count} {$host}";
    }
    return $command;
}
$command = osAwarePing('example.com');
$output = shell_exec($command);
echo "<pre>{$output}

"; ?>

Security considerations

Input validation: always validate user‑provided input.

Escape arguments: use escapeshellarg() to escape parameters.

Permission restriction: run the script with the minimum necessary privileges.

A safer version that validates input and escapes the host name:

<?php
function safePing($host, $count = 4) {
    if (!is_numeric($count) || $count < 1 || $count > 10) {
        return ['error' => 'Invalid ping count'];
    }
    if (!preg_match('/^[a-zA-Z0-9\-.]+$/', $host)) {
        return ['error' => 'Invalid hostname or IP address'];
    }
    $host = escapeshellarg($host);
    $count = (int)$count;
    $command = osAwarePing($host, $count);
    return shell_exec($command);
}
?>

Visualization output

To improve user experience, the ping results can be displayed in a friendly HTML format:

<?php
function displayPingResult($pingData) {
    if (isset($pingData['error'])) {
        echo "<div class='error'>{$pingData['error']}</div>";
        return;
    }
    echo "<div class='ping-result'>";
    echo "<h2>Ping Results for {$pingData['host']}</h2>";
    echo "<p>Packets: {$pingData['packets_transmitted']} sent, {$pingData['packets_received']} received, {$pingData['packet_loss']}% loss</p>";
    if (!empty($pingData['round_trip'])) {
        echo "<p>Round Trip Times (ms):<ul>";
        echo "<li>Min: {$pingData['round_trip']['min']}</li>";
        echo "<li>Avg: {$pingData['round_trip']['avg']}</li>";
        echo "<li>Max: {$pingData['round_trip']['max']}</li>";
        echo "<li>Mdev: {$pingData['round_trip']['mdev']}</li>";
        echo "</ul></p>";
    }
    if (!empty($pingData['details'])) {
        echo "<table border='1'><tr><th>Sequence</th><th>TTL</th><th>Time (ms)</th></tr>";
        foreach ($pingData['details'] as $detail) {
            echo "<tr><td>{$detail['sequence']}</td><td>{$detail['ttl']}</td><td>{$detail['time']}</td></tr>";
        }
        echo "</table>";
    }
    echo "</div>";
}
$pingData = structuredPing('google.com');
displayPingResult($pingData);
?>

By executing ping with PHP and structuring its output, developers can build powerful network diagnostic tools. The article covers everything from basic execution to advanced parsing, cross‑platform handling, and security, providing a foundation for extending to other system commands and creating comprehensive monitoring solutions.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentpingSecuritysystem commandsNetwork Diagnostics
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.