从PHP cURL响应中获取标头

Tua*_*inh 14 php curl header response

我是PHP的新手.我发送php curl POST请求后尝试从响应中获取Header.客户端将请求发送到服务器,服务器使用Header发回响应.这是我发送POST请求的方式.

   $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);
Run Code Online (Sandbox Code Playgroud)

这是我从浏览器获得的服务器的头响应

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) 
Run Code Online (Sandbox Code Playgroud)

如何从标题中提取授权部分?我需要将它存储在cookie中

Tha*_*vam 29

它将所有标头转换为数组

// 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>";
Run Code Online (Sandbox Code Playgroud)

  • 我的编辑被拒绝,因为@ user75ponic认为它是"多余的".对不起,但他错了.@Thamaraiselvam正如我之前的评论所述,您的代码不会考虑尾部返回中可能且通常存在的尾随换行符.尾随换行符的存在会导致此代码完全中断.使用`rtrim($ output)`来解决这个问题.您也根本不处理空值,如果任何标头包含空值,您将收到PHP警告,这也是一种可能性.你可以像这样处理:`if(!isset($ middle [1])){$ middle [1] = null; }`. (6认同)