PHP file_get_contents() and setting request headers

Marcus picture Marcus · Jan 21, 2010 · Viewed 183.6k times · Source

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?

Answer

Dominic Barnes picture Dominic Barnes · Jan 21, 2010

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

// Create a stream
$opts = [
    "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n" .
            "Cookie: foo=bar\r\n"
    ]
];

// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$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)