What are the best practices for handling timeouts and preventing feof from hanging in a TcpSocket connection in PHP?

When working with TcpSocket connections in PHP, it is important to handle timeouts properly to prevent the script from hanging indefinitely. One common issue is when using feof to check for the end of a stream, which can cause the script to hang if the connection is lost. To prevent this, it is recommended to set a timeout for the socket connection and check for timeouts before attempting to read or write data.

// Set a timeout for the socket connection
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 1, "usec" => 0));

// Check for timeouts before reading data
if (socket_select($read, $write, $except, 1) === false) {
    // Handle timeout or error
    die("Socket timeout or error");
}

// Check for end of stream before reading
while (!feof($socket)) {
    // Read data from socket
    $data = socket_read($socket, 1024);
    
    // Process data
    // ...
}