DEV Community

Jake Casto
Jake Casto

Posted on

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

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);
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
danvaly profile image
Valentin Ghica • Edited

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.