Get header from PHP cURL response

I am new to PHP. I am trying to get a header from a response after sending a php curl POST request. The client sends a request to the server, and the server sends a response with a header. This is how I sent my POST request.

   $client = curl_init($url);  
   curl_setopt($client, CURLOPT_CUSTOMREQUEST, "POST");
   curl_setopt($client, CURLOPT_POSTFIELDS, $data_string);
   curl_setopt($client, CURLOPT_HEADER, 1);
   $response = curl_exec($client);
   var_dump($response);

Here is the response of the server header that I get from the browser

HTTP/1.1 200 OK 
Date: Wed, 01 Feb 2017 11:40:59 GMT 
Authorization: eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2Vycy9CYW9CaW5oMTEwMiIsIm5hbWUiOiJhZG1pbiIsInBhc3N3b3JkIjoiMTIzNCJ9.kIGghbKQtMowjUZ6g62KirdfDUA_HtmW-wjqc3ROXjc Content-Type: text/html;charset=utf-8 Transfer-Encoding: chunked Server: Jetty(9.3.6.v20151106) 

How to extract authorization part from header? I need to save it in cookies

+14
source share
4 answers

It converts all headers to an array

// create curl resource
$ch = curl_init();

// set url
curl_setopt($ch, CURLOPT_URL, "example.com");

//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//enable headers
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// $output contains the output string
$output = curl_exec($ch);

// close curl resource to free up system resources
curl_close($ch);

$headers = [];
$output = rtrim($output);
$data = explode("\n",$output);
$headers['status'] = $data[0];
array_shift($data);

foreach($data as $part){

    //some headers will contain ":" character (Location for example), and the part after ":" will be lost, Thanks to @Emanuele
    $middle = explode(":",$part,2);

    //Supress warning message if $middle[1] does not exist, Thanks to @crayons
    if ( !isset($middle[1]) ) { $middle[1] = null; }

    $headers[trim($middle[0])] = trim($middle[1]);
}

// Print all headers as array
echo "<pre>";
print_r($headers);
echo "</pre>";
+29
source

For the first answer, note that the code:

$middle=explode(":",$part);

will lead to incorrect results with string data containing :for example, for example:

Sat, 14 Jan 2017 01:10:01 GMT

:

$middle=explode(":",$part,2);
+3

curl_setopt($curl_exec, CURLOPT_HEADER, true); 
curl_setopt($curl_exec, CURLOPT_NOBODY, true);

curl $header_data= curl_getinfo($curl_exec);

print_r($header_data);

shell_exec

echo shell_exec("curl -I http://example.com ");
0

curl .

 $response  = curl_exec($ch);
 $header_data= curl_getinfo($ch);
 print_r($header_data);
-2

Source: https://habr.com/ru/post/1668507/


All Articles