[英]PHP GET Request, sending headers
我需要執行一個get請求,並發送標頭。 我該怎么做?
我需要設置的主要標題是瀏覽器之一。 是否有捷徑可尋?
如果使用的是cURL,則可以使用curl_setopt ($handle, CURLOPT_USERAGENT, 'browser description')
來定義請求的用戶代理標頭。
如果您使用的是file_get_contents
,請在手冊頁中查看file_get_contents的示例調整:
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n" .
"User-agent: BROWSER-DESCRIPTION-HERE\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
如果要請求頁面,請使用cURL 。
為了設置標頭(在這種情況下,HTTP請求中的User-Agent
標頭),您可以使用以下語法:
<?php
$curl_h = curl_init('http://www.example.com/');
curl_setopt($curl_h, CURLOPT_HTTPHEADER,
array(
'User-Agent: NoBrowser v0.1 beta',
)
);
# do not output, but store to variable
curl_setopt($curl_h, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl_h);
您可以為此使用header
函數,例如:
header('Location: http://www.example.com?var=some_value');
注意:
請記住,必須先通過常規HTML標記,文件中的空白行或從PHP發送任何實際輸出,然后調用header()。 使用include()或require(),函數或另一個文件訪問函數讀取代碼,並在調用header()之前輸出空格或空行,這是一個非常常見的錯誤。 使用單個PHP / HTML文件時,存在相同的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.