I need to perform a get request and send headers along with it. What can I use to do this?
The开发者_高级运维 main header I need to set is the browser one. Is there an easy way to do this?
If you're using cURL, you can use curl_setopt ($handle, CURLOPT_USERAGENT, 'browser description')
to define the user-agent header of the request.
If you're using file_get_contents
, check out this tweak of an example on the man page for 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);
If you are requesting a page, use cURL.
In order to set the headers (in this case, the User-Agent
header in the HTTP request, you would use this syntax:
<?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);
You can use the header
function for that, example:
header('Location: http://www.example.com?var=some_value');
Note that:
Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with include(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file.
精彩评论