Home  >  Q&A  >  body text

PHP cURL: Read specific response header information

<p>I'm using cURL in PHP to make a POST request to send data to a terminal that creates a resource. It returns a 201 response with a Location header which gives the URL of the resource created. I also get some information from the body of the response. <br /><br />How best to get the plain text body of the response, and get the value of the Location header? The curl_getinfo function fails to return information for this header when I try to do this: </p><p><br /></p> <pre class="brush:php;toolbar:false;">curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($ch, $header) { var_dump($header); });</pre> <p>I only see one header being output, which is the response code of "HTTP/1.1 201 Created". </p>
P粉395056196P粉395056196463 days ago471

reply all(1)I'll reply

  • P粉713866425

    P粉7138664252023-08-07 11:27:20

    $ch = curl_init();
    
    curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER,true);
    
    $result = curl_exec($ch);
    
    curl_close($ch);
    
    list($headers, $content) = explode("\r\n\r\n",$result,2);
    
    // Print header
    foreach (explode("\r\n",$headers) as $hdr)
        printf('<p>Header: %s</p>', $hdr);
    
    // Print Content
    echo $content;

    reply
    0
  • Cancelreply