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.


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('', false, $context);
Enter fullscreen mode Exit fullscreen mode

Latest comments (1)

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.

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.