tags:

views:

784

answers:

6

With PHP, is it possible to send HTTP headers with file_get_contents() ?

I know you can send the user agent from your php.ini file. However, can you also send other information such as HTTP_ACCEPT, HTTP_ACCEPT_LANGUAGE, and HTTP_CONNECTION with file_get_contents() ?

Or is there another function that will accomplish this?

+6  A: 

You might want to look into cUrl - it will give you a far greater flexibility than file_get_contents

Marek Karbarz
+1  A: 

Unfortunately, it doesn't look like file_get_contents() really offers that degree of control. The cURL extension is usually the first to come up, but I would highly recommend the PECL_HTTP extension (http://pecl.php.net/package/pecl_http) for very simple and straightforward HTTP requests. (it's much easier to work with than cURL)

Dominic Barnes
+1  A: 

Using the php cURL libraries will probably be the right way to go, as this library has more features than the simple file_get_contents(...).

An example:

<?php
$ch = curl_init();
$headers = array('HTTP_ACCEPT: Something', 'HTTP_ACCEPT_LANGUAGE: fr, en, da, nl', 'HTTP_CONNECTION: Something');

curl_setopt($ch, CURLOPT_URL, "http://localhost"); # URL to post to
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt($ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
$result = curl_exec( $ch ); # run!
curl_close($ch);
?>
phidah
+3  A: 

Actually, upon further reading on the file_get_contents() function:

<?php
// Create a stream
$opts = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\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);
?>

You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)

Dominic Barnes
see also: http://docs.php.net/context and http://docs.php.net/stream_context_create
VolkerK
A: 

send header using linux command: wget in php file like.
exec('wet'--referer "www.example.com");

neverSayNo
A: 

If you don't need HTTPS and curl is not available on your system you could use fsockopen (http://de2.php.net/manual/en/function.fsockopen.php).

This function opens a connection from which you can both read and write like you would do with a normal file handle.

alexb