[英]Receiving HTTP Request headers in PHP
我將cURL用於自定義HTTP標頭請求。 但是如何獲取PHP以顯示標題?
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('my_key: 12345'));
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLINFO_HEADER_OUT, true);
$response = curl_exec($ch);
curl_close($ch);
echo $response;
echo "<br><br>";
if($_SERVER['my_key']=='12345'){
echo 'Key is OK';
} else {
echo 'Key is wrong';
}
// also tried!
print_r($_COOKIE);
var_dump (curl_getinfo($ch));
?>
我想對您來說更簡單的方法可能是guzzle
。 您可以執行以下操作:
$client = new GuzzleHttp\Client();
$res = $client->get('https://api.github.com/user', ['auth' => ['user', 'pass']]);
echo $res->getStatusCode(); // "200"
echo $res->getHeader('content-type'); // 'application/json; charset=utf8'
echo $res->getBody(); // {"type":"User"...'
在docs中有更多信息。
以其他方式,您可以檢查此解決方案 。
如果您確實希望獲取請求,但不想獲取響應標頭,則應嘗試以下代碼:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://www.google.com/');
curl_setopt($ch, CURLINFO_HEADER_OUT, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_getinfo ($ch);
/*[
"url" => "http://www.google.com/",
"content_type" => "text/html; charset=UTF-8",
"http_code" => 302,
"header_size" => 267,
...
"redirect_url" => "http://www.google.com.ua/?gfe_rd=cr&ei=-fClVYDfA9eEtAH65oGQAQ",
"request_header" => "GET / HTTP/1.1\r\nHost: www.google.com\r\nAccept: * /*\r\n\r\n"
]*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.