Attila Szeremi
Attila Szeremi

Reputation: 5488

Getting the request headers send via file_get_contents()

When using file_get_contents() to request an external URL, how can I find out what headers I've sent, or alternatively what headers I am about to send? I'm basically looking for a request counterpart for $http_response_header or anything else I can use to extract the same data.

I know I get to set headers myself with stream_context_create(array ('http' => array ('header' => $header))), but I want to see what headers are actually being sent in the end, including default ones.

Upvotes: 3

Views: 3433

Answers (1)

Latheesan
Latheesan

Reputation: 24116

If you need a consistent header to go out with each file_get_contents request, use the stream contexts like this example:

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

?>

Src: http://php.net/manual/en/function.file-get-contents.php


If you want to see what headers you are sending, the best option I can think of involves curl (not file_get_contents), which looks like this:

When making the request; set this option:

curl_setopt($ch, CURLINFO_HEADER_OUT, true);

Then you can debug the request and see what headers were sent using this (after the request was sent):

var_dump(curl_getinfo($ch));

More info: http://www.php.net/manual/en/function.curl-getinfo.php

Upvotes: 1

Related Questions