title: What's the canonical way to put a read timeout on a stream in PHP?
body: <p>Here's some sample code:</p>
  
  <pre><code>&lt;?php
  $fp = fsockopen($host, $port, $errno, $errstr, $connectTimeout);
  
  if (!$fp) {
      echo "$errstr ($errno)&lt;br /&gt;\n";
  } else {
      echo "connected\n"; 
      while (!feof($fp)) {
          echo fgets($fp, 128);
      }
      fclose($fp);
  }
  </code></pre>
  
  <p>I've seen
  <code>stream_set_timeout($fp, 5);</code> and<br>
  <code>socket_set_option($fp, SOL_SOCKET, SO_RCVTIMEO, array("sec"=&gt;5, "usec"=&gt;0));</code>,
  but the read never times out.</p>
  
  <p>I've seen several caveats in the PHP docs for <code>stream_set_timeout()</code>:</p>
  
  <blockquote>
    <p>This function doesn't work with advanced operations like
    stream_socket_recvfrom(), use stream_select() with timeout parameter instead.</p>
  </blockquote>
  
  <p>I'd rather not use <code>select()</code> or a loop. What is the canonical way to have a blocking read with timeout?</p>