title: How to isolate the HTTP headers/body from a PHP Sockets request
body: <p>I'm using a socket connection in PHP to post data to an Apache webserver. I'm a bit new to this technique, and I am not sure how to isolate the headers from the body of the response.</p>
  
  <p>Sending Code:</p>
  
  <pre><code>&lt;?php
  // collect data to post
  $postdata = array(
      'hello' =&gt; 'world'
  );
  $postdata = http_build_query($postdata);
  // open socket, send request
  $fp = fsockopen('127.0.0.1', 80);
  fwrite($fp, "POST /server.php HTTP/1.1\r\n");
  fwrite($fp, "Host: fm1\r\n");
  fwrite($fp, "Content-Type: application/x-www-form-urlencoded\r\n");
  fwrite($fp, "Content-Length: ".strlen($postdata)."\r\n");
  fwrite($fp, "Connection: close\r\n");
  fwrite($fp, "\r\n");
  fwrite($fp, $postdata);
  // go through result
  $result = "";
  while(!feof($fp)){
      $result .= fgets($fp);
  }
  // close
  fclose($fp);
  // display result
  echo $result;
  ?&gt;
  </code></pre>
  
  <p>Server Code:</p>
  
  <pre><code>Hello this is server. You posted:
  &lt;pre&gt;
  &lt;?php print_r($_POST); ?&gt;
  &lt;/pre&gt;
  </code></pre>
  
  <p>When posting to one server, I get:</p>
  
  <pre><code>HTTP/1.1 200 OK
  Date: Fri, 06 Jan 2012 09:55:27 GMT
  Server: Apache/2.2.15 (Win32) mod_ssl/2.2.15 OpenSSL/0.9.8m PHP/5.3.2
  X-Powered-By: PHP/5.3.2
  Content-Length: 79
  Connection: close
  Content-Type: text/html
  
  Hello this is server. You posted:
  &lt;pre&gt;
  Array
  (
      [hello] =&gt; world
  )
  &lt;/pre&gt;
  </code></pre>
  
  <p>As expected. I want to strip off the headers though, and just read the body from "Hello this is server....." onwards.
  How can i reliably detect the end of the headers and read the body into a variable?</p>
  
  <p>Also, another server I've tested on replies with this:</p>
  
  <pre><code>HTTP/1.1 200 OK
  Date: Fri, 06 Jan 2012 10:02:04 GMT
  Server: Apache/2
  X-Powered-By: PHP/5.2.17
  Connection: close
  Transfer-Encoding: chunked
  Content-Type: text/html
  
  4d
  Hello this is server. You posted:
  &lt;pre&gt;
  Array
  (
      [hello] =&gt; world
  )
  &lt;/pre&gt;
  0
  </code></pre>
  
  <p>What are the "4d" and "0" around the body text??</p>
  
  <p>Thanks!</p>
  
  <p>PS before someone says use CURL, I can't unfortunately :-(</p>