What are the best practices for handling timeouts in PHP scripts, especially when dealing with external connections like fsockopen?

When dealing with external connections like fsockopen in PHP scripts, it's important to handle timeouts properly to prevent the script from hanging indefinitely. One way to handle timeouts is to set a timeout value for the connection using the stream_set_timeout function. This will allow the script to wait for a specified amount of time before timing out and moving on to the next task.

// Set timeout value for fsockopen connection
$timeout = 5; // 5 seconds timeout
$socket = fsockopen('example.com', 80, $errno, $errstr, $timeout);

if (!$socket) {
    // Handle connection timeout error
    echo "Connection timeout: $errstr ($errno)";
} else {
    // Connection successful, continue with the script
    fwrite($socket, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
    $response = fread($socket, 4096);
    
    // Close the connection
    fclose($socket);
}