How can the fsockopen function be optimized to handle TCP connection failures more efficiently?

To handle TCP connection failures more efficiently when using the fsockopen function, it is important to set a timeout value for the connection attempt. This will prevent the script from hanging indefinitely if the connection cannot be established. Additionally, using error handling techniques such as try-catch blocks can help to gracefully handle connection failures and provide appropriate feedback to the user.

<?php

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

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

if (!$socket) {
    throw new Exception("Failed to connect to $host: $errstr ($errno)");
}

// Continue with sending/receiving data over the socket

fclose($socket);

?>