What are some best practices for using fsockopen() function in PHP to check server status?

When using the fsockopen() function in PHP to check server status, it is important to handle potential errors and timeouts gracefully. One best practice is to set a timeout value to prevent the script from hanging indefinitely if the server is unresponsive. Additionally, checking the return value of fsockopen() and properly closing the socket connection are important steps to ensure proper functionality.

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

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

if ($socket) {
    echo "Server is reachable";
    fclose($socket);
} else {
    echo "Server is not reachable: $errstr ($errno)";
}