有些时候我们需要响应头的数据来做下一步的功能,比如有些api在响应头中包含了token。那么如何解析响应头数据并得到token呢?参照如下方法得到响应数据,并从中获取想要的key值。
$url = 'https://10.1pxeye.com'; // 请求地址,换成自己的。
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_HEADER => 1,
CURLOPT_NOBODY => 0,
CURLOPT_POSTFIELDS => '{}',
CURLOPT_HTTPHEADER => ['Content-Type:application/json;charset=utf-8'],
)
);
$response = curl_exec($curl);
curl_close($curl);
$header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$response_headers = [];
$line = strtok($header, "\r\n");
$status_code = trim($line);
while (($line = strtok("\r\n")) !== false) {
if (false !== ($matches = explode(':', $line, 2))) {
$response_headers["{$matches[0]}"] = trim($matches[1]);
}
}
echo '<pre style="font-size:12px;line-height:1.3">';
print_r($response_headers);
echo '<pre>';
上述代码将得到如下类型数据:
Array
(
[Date] => Fri, 22 Dec 2023 04:43:37 GMT
[Server] => Apache
[Link] => ; rel="https://api.w.org/", ; rel="alternate"; type="application/json", ; rel=shortlink
[Strict-Transport-Security] => max-age=31536000; includeSubDomains;
[Upgrade] => h2
[Connection] => Upgrade, close
[Cache-Control] => max-age=0
[Vary] => Accept-Encoding
[X-XSS-Protection] => 1; mode=block
[X-Content-Type-Options] => nosniff
[X-Frame-Options] => SAMEORIGIN
[Access-Control-Allow-Origin] => https://cdn.10.1pxeye.com, https://media.1pxeye.com
[Content-Security-Policy] => connect-src 'self' *.1pxeye.com
[Referrer-Policy] => no-referrer-when-downgrade
[Permissions-Policy] => microphone=(),camera=()
[Transfer-Encoding] => chunked
[Content-Type] => text/html; charset=UTF-8
)
评论区
发表新的留言
您可以留言提出您的疑问或建议。
您的留言得到回复时,会通过您填写的邮箱提醒您。