How can the PHP script be modified to accurately display the online and offline status of servers, especially when dealing with different protocols like UDP?

To accurately display the online and offline status of servers, especially when dealing with different protocols like UDP, you can modify the PHP script to use socket functions to check the server's status. By creating a socket connection to the server and checking for a response, you can determine if the server is online or offline. Additionally, you can set a timeout for the socket connection to handle cases where the server may not respond.

<?php

function checkServerStatus($serverIP, $port, $protocol) {
    $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname($protocol));
    socket_set_nonblock($socket);
    socket_connect($socket, $serverIP, $port);

    $read = [$socket];
    $write = $except = null;

    if (socket_select($read, $write, $except, 5) === 1) {
        $status = "Online";
    } else {
        $status = "Offline";
    }

    socket_close($socket);

    return $status;
}

// Example usage
$serverIP = "127.0.0.1";
$port = 80;
$protocol = "tcp";
$status = checkServerStatus($serverIP, $port, $protocol);
echo "Server status: " . $status;

?>