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

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

    Here is my contribution to the debate ... This returns a single array with the data separated and the headers listed. This works on the basis that CURL will return a headers chunk [ blank line ] data

    curl_setopt($ch, CURLOPT_HEADER, 1); // we need this to get headers back
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    
    // $output contains the output string
    $output = curl_exec($ch);
    
    $lines = explode("\n",$output);
    
    $out = array();
    $headers = true;
    
    foreach ($lines as $l){
        $l = trim($l);
    
        if ($headers && !empty($l)){
            if (strpos($l,'HTTP') !== false){
                $p = explode(' ',$l);
                $out['Headers']['Status'] = trim($p[1]);
            } else {
                $p = explode(':',$l);
                $out['Headers'][$p[0]] = trim($p[1]);
            }
        } elseif (!empty($l)) {
            $out['Data'] = $l;
        }
    
        if (empty($l)){
            $headers = false;
        }
    }
    
    0 讨论(0)
  • 2020-11-22 03:36

    The problem with many answers here is that "\r\n\r\n" can legitimately appear in the body of the html, so you can't be sure that you're splitting headers correctly.

    It seems that the only way to store headers separately with one call to curl_exec is to use a callback as is suggested above in https://stackoverflow.com/a/25118032/3326494

    And then to (reliably) get just the body of the request, you would need to pass the value of the Content-Length header to substr() as a negative start value.

    0 讨论(0)
  • 2020-11-22 03:36

    Return response headers with a reference parameter:

    <?php
    $data=array('device_token'=>'5641c5b10751c49c07ceb4',
                'content'=>'测试测试test'
               );
    $rtn=curl_to_host('POST', 'http://test.com/send_by_device_token', array(), $data, $resp_headers);
    echo $rtn;
    var_export($resp_headers);
    
    function curl_to_host($method, $url, $headers, $data, &$resp_headers)
             {$ch=curl_init($url);
              curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $GLOBALS['POST_TO_HOST.LINE_TIMEOUT']?$GLOBALS['POST_TO_HOST.LINE_TIMEOUT']:5);
              curl_setopt($ch, CURLOPT_TIMEOUT, $GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']?$GLOBALS['POST_TO_HOST.TOTAL_TIMEOUT']:20);
              curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
              curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
              curl_setopt($ch, CURLOPT_HEADER, 1);
    
              if ($method=='POST')
                 {curl_setopt($ch, CURLOPT_POST, true);
                  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
                 }
              foreach ($headers as $k=>$v)
                      {$headers[$k]=str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $k)))).': '.$v;
                      }
              curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
              $rtn=curl_exec($ch);
              curl_close($ch);
    
              $rtn=explode("\r\n\r\nHTTP/", $rtn, 2);    //to deal with "HTTP/1.1 100 Continue\r\n\r\nHTTP/1.1 200 OK...\r\n\r\n..." header
              $rtn=(count($rtn)>1 ? 'HTTP/' : '').array_pop($rtn);
              list($str_resp_headers, $rtn)=explode("\r\n\r\n", $rtn, 2);
    
              $str_resp_headers=explode("\r\n", $str_resp_headers);
              array_shift($str_resp_headers);    //get rid of "HTTP/1.1 200 OK"
              $resp_headers=array();
              foreach ($str_resp_headers as $k=>$v)
                      {$v=explode(': ', $v, 2);
                       $resp_headers[$v[0]]=$v[1];
                      }
    
              return $rtn;
             }
    ?>
    
    0 讨论(0)
  • 2020-11-22 03:38

    Just set options :

    • CURLOPT_HEADER, 0

    • CURLOPT_RETURNTRANSFER, 1

    and use curl_getinfo with CURLINFO_HTTP_CODE (or no opt param and you will have an associative array with all the informations you want)

    More at : http://php.net/manual/fr/function.curl-getinfo.php

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 03:45

    Curl has a built in option for this, called CURLOPT_HEADERFUNCTION. The value of this option must be the name of a callback function. Curl will pass the header (and the header only!) to this callback function, line-by-line (so the function will be called for each header line, starting from the top of the header section). Your callback function then can do anything with it (and must return the number of bytes of the given line). Here is a tested working code:

    function HandleHeaderLine( $curl, $header_line ) {
        echo "<br>YEAH: ".$header_line; // or do whatever
        return strlen($header_line);
    }
    
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.google.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, "HandleHeaderLine");
    $body = curl_exec($ch); 
    

    The above works with everything, different protocols and proxies too, and you dont need to worry about the header size, or set lots of different curl options.

    P.S.: To handle the header lines with an object method, do this:

    curl_setopt($ch, CURLOPT_HEADERFUNCTION, array(&$object, 'methodName'))
    
    0 讨论(0)
提交回复
热议问题