Get Header from PHP cURL response(从 PHP cURL 响应中获取标头)
问题描述
我是 PHP 新手.在发送 php curl POST 请求后,我试图从响应中获取 Header.客户端将请求发送到服务器,服务器将带有 Header 的响应发回.以下是我发送 POST 请求的方式.
I am new to PHP. I am trying to get the Header from the response after sending the php curl POST request. The client sends the request to the server and server sends back the response with Header. Here 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);
这是我从浏览器获得的来自服务器的 Header 响应
Here is the Header response from server 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)
如何从 Header 中提取 Authorization 部分?我需要将其存储在 cookie 中
How can I extract the Authorization part from the Header ?. I need to store it in the cookies
推荐答案
它将所有的headers转换成一个数组
It converts all headers into 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("
",$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>";
这篇关于从 PHP cURL 响应中获取标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 PHP cURL 响应中获取标头
- Mod使用GET变量将子域重写为PHP 2021-01-01
- PHP Count 布尔数组中真值的数量 2021-01-01
- Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
- 正确分离 PHP 中的逻辑/样式 2021-01-01
- SoapClient 设置自定义 HTTP Header 2021-01-01
- 没有作曲家的 PSR4 自动加载 2022-01-01
- 带有通配符的 Laravel 验证器 2021-01-01
- 从 PHP 中的输入表单获取日期 2022-01-01
- Laravel 仓库 2022-01-01
- 如何定位 php.ini 文件 (xampp) 2022-01-01