James Jeffery
James Jeffery

Reputation: 435

PHP GET Request, sending headers

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?

Upvotes: 36

Views: 68886

Answers (3)

amphetamachine
amphetamachine

Reputation: 30575

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

Upvotes: 13

grossvogel
grossvogel

Reputation: 6782

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

Upvotes: 62

Sarfraz
Sarfraz

Reputation: 382606

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.

Upvotes: -5

Related Questions