title: How to get the HTTP request as a string from PHP HTTP Stream
body: <p>I'm using PHP Streams to make HTTP calls with fopen().  I would like print the HTTP request as a string (headers and content) before it is sent via fopen().  </p>
  
  <p>Is there a function that handles the stream context variable to do this?  If so, would someone be kind enough to post a brief example of this? </p>
  
  <p>Here is a function that expects a URL, fetches it and returns the content:</p>
  
  <pre><code>function do_post_request ($url, $content, $cookie = null) {
    $headers = array("Content-type: application/x-www-form-urlencoded",
                     $cookie);
  
    $all_headers = implode("\r\n", $headers)."\r\n";
    $params = array('http' =&gt; array("method" =&gt; "POST",
                                    "content" =&gt; $content,
                                    "header" =&gt; $all_headers,
                                   ),
                   );
  
    $ctx = stream_context_create($params);
    $fp = fopen($url, 'rb', false, $ctx);
    if (empty($fp)) {
      throw new Exception("$url: Failed");
    }
    $resp = stream_get_contents($fp);
  
    if (empty($resp)) {
      throw new Exception("error: bad fetch");
    }
    return $resp
  }
  </code></pre>