What are the best practices for error handling when using fsockopen in PHP?

When using fsockopen in PHP, it is important to implement proper error handling to catch any potential issues that may arise, such as connection timeouts or errors. This can be done by checking the return value of fsockopen and using functions like stream_get_meta_data to retrieve error information. Additionally, utilizing try-catch blocks can help in handling exceptions gracefully.

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

if(!$socket) {
    // Error handling
    echo "Error: $errstr ($errno)";
} else {
    // Successful connection
    // Additional code here
    fclose($socket);
}