从PHP cURL响应中获取标头

时间:2017-02-01 11:43:19

标签: php curl header response

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

<input type="text" class="input-xxlarge text-center" >

以下是我从浏览器获取的服务器的Header响应

   $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);

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

4 个答案:

答案 0 :(得分:26)

它将所有标题转换为数组

// 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>";

答案 1 :(得分:3)

对于第一个答案,请注意代码:

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

对于包含:的字符串数据,将产生错误的结果,例如:

Sat, 14 Jan 2017 01:10:01 GMT

用于拆分字段以构建数组的正确代码如下:

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

答案 2 :(得分:1)

您只需将此编码包含在您的卷曲请求中

curl_setopt($curl_exec, CURLOPT_HEADER, true); 
curl_setopt($curl_exec, CURLOPT_NOBODY, true);
执行卷曲后

使用$header_data= curl_getinfo($curl_exec);

然后你得到所有标题

print_r($header_data);

或使用shell_exec

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

答案 3 :(得分:-2)

只需使用简单的代码即可将curl响应转换为数组。

input_fn