Beware: stream_copy_to_stream and Zend_Http_Client_Adapter_Socket may hang on old PHP 5.2.x

Recently we found that our Zend Framework based application was running into infinite loop and terminated by execution timeout on some hostings. The problem was found in Zend_Http_Client_Adapter_Socket class which uses stream_copy_to_stream if you configure Zend_Http_Client for writing data to stream.

The problem already was reported on ZF issue tracker but wasn’t fixed: http://framework.zend.com/issues/browse/ZF-9265.
It seems that the cause is a bug in stream_copy_to_stream that was fixed at some point during PHP 5.2.x development.

But as we need to run our code on virtually any hosting we decided to work around this problem by replacing stream_copy_to_stream with fread and fwrite in Zend_Http_Client_Adapter_Socket code.
Notice that Zend_Http_Client_Adapter_Curl is not affected by this problem as it uses internal code for writing to streams. Thus, switching to Zend_Http_Client_Adapter_Curl sounds as the easiest solution. We added automatic switching to it by checking if ‘curl_init’ function exists and if so we use Zend_Http_Client_Adapter_Curl as the adapter for Zend_Http_Client.