Are there any alternative methods or libraries that can be used for pinging in PHP, aside from the exec() function?

Using the exec() function in PHP to ping a server can be a security risk as it allows for arbitrary commands to be executed on the server. An alternative method to ping a server in PHP is to use the fsockopen() function to open a socket connection to the server and check for a response. This method is safer and more secure than using exec().

function pingServer($host, $port){
    $fp = @fsockopen($host, $port, $errno, $errstr, 1);
    if ($fp) {
        fclose($fp);
        return true;
    } else {
        return false;
    }
}

$host = 'example.com';
$port = 80;

if(pingServer($host, $port)){
    echo "Server is reachable";
} else {
    echo "Server is not reachable";
}