loading...

Using Headers & Cookies with PHP's file_get_contents() function

jake profile image Jake Casto ・1 min read

This solution was originally linked to me by a colleague, all credit goes to this tweet.

image

Did you know that using stream contexts, you can set headers when making HTTP requests with php's file_get_contents() function?

$context = stream_create_context([
    "http" => [
        "method" => "GET",
        "header" => "Accept-languange: en\r\n" .
        "Cookie: foo=bar\r\n"
    ]
]);

$file = file_get_contents('https://example.com', false, $context);

Discussion

pic
Editor guide
 

Hello, the function is stream_context_create not stream_create_context.
Verry nice solution. I had an environment that doesn't allow curl and this solution work like a charm.