Are there any best practices or alternative methods to handle errors and prevent error messages like "unable to connect" when using fsockopen?

When using fsockopen to establish a network connection, errors like "unable to connect" can occur due to various reasons such as network issues or incorrect server configurations. To handle these errors and prevent error messages, it is recommended to use error handling techniques like try-catch blocks and checking for specific error codes.

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

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

if (!$socket) {
    if ($errno == 110) {
        // Handle specific error code 110
        echo "Connection timed out";
    } else {
        // Handle other connection errors
        echo "Unable to connect: $errstr ($errno)";
    }
} else {
    // Connection successful, proceed with data transfer
    fclose($socket);
}
?>