tags:

views:

52

answers:

3

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?

+1  A: 

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.

Sarfraz
I need to store the response from the request into a string for processing. So I cannot use this method.
James Jeffery
@James Jeffery: I don't understand what you mean by that, could you be more specific or add more details to your question? Thanks
Sarfraz
Are you trying to use AJAX? Or access PHP variables with Javascript?
Aaron Harun
+1  A: 

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);
grossvogel
Thanks solved :)
James Jeffery
A: 

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);
amphetamachine