当存在多个标头时,如何将cURL标头与主体分开

There are many questions on here asking how to separate the header of a cURL response from the body and the two methods I've seen are:

  1. Use the length of the header and substr()

  2. Use explode(" ", $response, 2)

However, the first method doesn't work when a proxy server is being used, and the second doesn't work when a 302 redirect is performed by the server and FOLLOW_LOCATION is set.

Therefore, my following code is insufficient, as the additional headers end up in $body:

$data      = explode("

", $response, 2);
$header    = $data[0];
$body      = $data[1];

My current line of thought is to put the above code in a loop and after each iteration check if the first part of $body is HTTP, as the headers always look like:

HTTP/1.1 100 Continue
HTTP/1.1 302 Moved Temporarily
HTTP/1.1 200 OK

If the first part of $body is HTTP/, then I would keep iterating, otherwise I would know that the headers had all been separated from the body. However, the downside I see to this is that if the body starts with HTTP/ (which I suppose is unlikely), then that would cause a major issue.

Is there a better solution than the one I'm currently thinking of pursuing?

As a side note, I'm doing this because I need to retrieve both the response body and header(s).