title: Curl_multi exits prematurely on file download
body: <p>When running file download to a file pointer using a single thread it works fine. When utilizing multithread it doesn't download the full file (stops somewhere in the middle)</p>
  
  <p>Single thread (works)</p>
  
  <pre><code>$fp = fopen('php://output', 'w');
  $ch = curl_init(str_replace(" ", "%20", $url)); //Here is the file we are downloading, replace spaces with %20
  curl_setopt($ch, CURLOPT_FILE, $fp);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  $return = curl_exec($ch); // get curl response
  $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
  $error = curl_error($ch);
  curl_close($ch);
  fclose($fp);
  </code></pre>
  
  <p>Multithread (incomplete download)</p>
  
  <pre><code>$bodyStream = fopen('php://output', 'w');
  $headerStream = fopen('php://temp', 'rw');
  
  $ch = curl_init(str_replace(" ", "%20", $url)); //Here is the file we are downloading, replace spaces with %20
  curl_setopt($ch, CURLOPT_WRITEHEADER, $headerStream);
  curl_setopt($ch, CURLOPT_FILE, $bodyStream);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  
  $mh = curl_multi_init();
  curl_multi_add_handle($mh, $ch);
  $headerProcessed = false;
  ob_start(); // Buffer body output until headers are ready
  do {
      $mrc = curl_multi_exec($mh, $active);
  } while ($mrc == CURLM_CALL_MULTI_PERFORM);
  
  while ($active &amp;&amp; $mrc == CURLM_OK) {
      do {
          $mrc = curl_multi_exec($mh, $active);
      } while ($mrc == CURLM_CALL_MULTI_PERFORM);
  
      // Process headers
      if (!$headerProcessed) {
          $currentPos = ftell($headerStream);
          rewind($headerStream);
          $header = stream_get_contents($headerStream);
          fseek($headerStream, $currentPos); // Is this really needed?
          if (strpos($header, "\r\n\r\n") !== false) {
              // Copy headers such as Content-Length etc.
              $this-&gt;generateProxyHeader($header);
  
              // Headers set. Now send output to browser
              $headerProcessed = true;
              ob_end_flush();
          }
      }
  }
  curl_multi_remove_handle($mh, $ch);
  curl_multi_close($mh);
  exit; // Download complete, stop processing
  </code></pre>
  
  <p>The main reason I need the headers prior to output is to catch errors on the backend. (Single threaded approach would result in 200OK header, even if server responds 404 or 500). This would effectively break the data in the file.</p>
  
  <p>How can I ensure the full file is sent to php://output before PHP stops sending data to browser, and still use the curl_multi (such that I can proxy large files, including headers)?</p>