Can PHP cURL retrieve response headers AND body in a single request?

后端 未结 13 1757
粉色の甜心
粉色の甜心 2020-11-22 03:28

Is there any way to get both headers and body for a cURL request using PHP? I found that this option:

curl_setopt($ch, CURLOPT_HEADER, true);
13条回答
  •  误落风尘
    2020-11-22 03:44

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    
    $parts = explode("\r\n\r\nHTTP/", $response);
    $parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
    list($headers, $body) = explode("\r\n\r\n", $parts, 2);
    

    Works with HTTP/1.1 100 Continue before other headers.

    If you need work with buggy servers which sends only LF instead of CRLF as line breaks you can use preg_split as follows:

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, 1);
    curl_setopt($ch, CURLOPT_HEADER, 1);
    
    $parts = preg_split("@\r?\n\r?\nHTTP/@u", $response);
    $parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
    list($headers, $body) = preg_split("@\r?\n\r?\n@u", $parts, 2);
    

提交回复
热议问题