What are the differences between using fsockopen() and a traditional ping command in PHP for server connectivity testing?

When testing server connectivity in PHP, using fsockopen() allows for more flexibility and control compared to a traditional ping command. fsockopen() enables you to specify the port number and protocol to test, while a ping command only checks if the server is reachable. Additionally, fsockopen() can handle more complex network scenarios and provide detailed error messages if the connection fails.

<?php
$host = 'example.com';
$port = 80;
$timeout = 5;

$fp = @fsockopen($host, $port, $errno, $errstr, $timeout);

if ($fp) {
    echo 'Connection successful!';
    fclose($fp);
} else {
    echo "Connection failed: $errstr ($errno)";
}
?>