[英]Get Header from PHP cURL 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);
這是我從瀏覽器獲得的服務器的頭響應
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)
如何從標題中提取授權部分? 我需要將它存儲在cookie中
它將所有標頭轉換為數組
// 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>";
對於第一個答案請注意代碼:
$middle=explode(":",$part);
將使用包含:
字符串數據生成錯誤的結果:
例如:
Sat, 14 Jan 2017 01:10:01 GMT
拆分字段以構建數組的正確代碼如下:
$middle=explode(":",$part,2);
您只需將此編碼包含在curl請求中即可
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 ");
只需使用簡單的代碼將curl響應轉換為數組。
$response = curl_exec($ch);
$header_data= curl_getinfo($ch);
print_r($header_data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.