我需要执行get请求并随之发送标头。我可以用它做什么?
我需要设置的主标题是浏览器。有一个简单的方法吗?
答案 0 :(得分:38)
如果您正在使用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);
答案 1 :(得分:5)
如果您要求页面,请使用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);
答案 2 :(得分:-4)
您可以使用 header
功能,例如:
header('Location: http://www.example.com?var=some_value');
请注意:
请记住,必须调用header() 在发送任何实际输出之前, 通过普通的HTML标签,空白 文件中的行,或来自PHP。它是一个 用于读取代码的常见错误 include(),或require(),函数或 另一个文件访问功能,并有 输出的空格或空行 在调用header()之前。相同 使用单个时存在问题 PHP / HTML文件。