What are the differences between using gethostbyname and fsockopen to test server availability in PHP?

When testing server availability in PHP, using gethostbyname may be a simpler and quicker method as it only requires the hostname as input and returns the IP address of the server. On the other hand, fsockopen allows for more control and customization as it establishes a socket connection to the server, allowing for additional checks such as port availability. Using fsockopen may be more reliable in determining server availability as it can handle various connection errors.

// Using gethostbyname to test server availability
$hostname = 'www.example.com';
$ip = gethostbyname($hostname);

if ($ip) {
    echo "Server is available at IP: $ip";
} else {
    echo "Server is not available";
}

// Using fsockopen to test server availability
$hostname = 'www.example.com';
$port = 80;
$timeout = 5;

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

if ($fp) {
    echo "Server is available";
    fclose($fp);
} else {
    echo "Server is not available";
}