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

后端 未结 13 1998
粉色の甜心
粉色の甜心 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:58

    Many of the other solutions offered this thread are not doing this correctly.

    • Splitting on \r\n\r\n is not reliable when CURLOPT_FOLLOWLOCATION is on or when the server responds with a 100 code.
    • Not all servers are standards compliant and transmit just a \n for new lines.
    • Detecting the size of the headers via CURLINFO_HEADER_SIZE is also not always reliable, especially when proxies are used or in some of the same redirection scenarios.

    The most correct method is using CURLOPT_HEADERFUNCTION.

    Here is a very clean method of performing this using PHP closures. It also converts all headers to lowercase for consistent handling across servers and HTTP versions.

    This version will retain duplicated headers

    This complies with RFC822 and RFC2616, please do not suggest edits to make use of the mb_ string functions, it is incorrect!

    $ch = curl_init();
    $headers = [];
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
    // this function is called by curl for each header received
    curl_setopt($ch, CURLOPT_HEADERFUNCTION,
      function($curl, $header) use (&$headers)
      {
        $len = strlen($header);
        $header = explode(':', $header, 2);
        if (count($header) < 2) // ignore invalid headers
          return $len;
    
        $headers[strtolower(trim($header[0]))][] = trim($header[1]);
    
        return $len;
      }
    );
    
    $data = curl_exec($ch);
    print_r($headers);
    

提交回复
热议问题