HTTPS read timeout

There is no timeout setting on a HTTPS connection, not even a default 60 seconds. This means that if the remote server does not answer for several minutes, the SOAP call also blocks several minutes. If we want a timeout on a HTTPS connection, we have to implement it ourselves.

To implement our own HTTPS client, we make use of the SSL functionality in fsockopen(). The function fsockopen() allows to set up a SSL connection and use it just like a normal connection. By connecting to port 443, the default HTTPS port, we can send HTTP commands to the remote server:

$socket = fsockopen('ssl://', 443);
fwrite($socket, "GET / HTTP/1.0\r\nHost:\r\n\r\n");
while ($data = fread($socket, 2000))
    echo $data;

The good thing is that fsockopen respects the default_socket_timeout setting, even in SSL mode. Alternatively, the timeout parameter to fsockopen can be used. However, we have to implement our own read timeout, because fread() will block forever if the remote server does not respond. Neither stream_set_timeout or default_socket_timeout will affect the reading of an SSL connection.

To implement timeout functionality, we can either use the stream_select() function or set the socket to non-blocking.