2017-02-01 138 views
4

我是PHP新手。我試圖在發送php curl POST請求後從響應中獲取Header。客戶端發送請求到服務器,服務器用Header發回響應。以下是我發送POST請求的方式。從PHP獲取頭文件cURL響應

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

讓我如何可以提取授權部分從郵件頭?我需要將其存儲在

+0

使用例如http://php.net/manual/en/function.preg-match.php –

+0

用換行符分解標題,用':'分隔每一行,檢查哪個標題被命名爲''Authorization「',取其值。 – deceze

+0

這可能很有用 - http://stackoverflow.com/a/11659510/297243 – Tom

回答

8

它所有的頭轉換成數組餅乾

// 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=array(); 

$data=explode("\n",$output); 

$headers['status']=$data[0]; 

array_shift($data); 

foreach($data as $part){ 
    $middle=explode(":",$part); 
    $headers[trim($middle[0])] = trim($middle[1]); 
} 

//print all headers as array 
echo "<pre>"; 
print_r($headers); 
echo "</pre>"; 
-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

這會獲取請求的標題而不是響應的標題。 – anierzad