Setting Multiple Headers in a PHP Stream Context

Last week I tried to create a PHP stream context which set multiple headers; an Authorization header and a Content-Type header. All the examples I could find showed headers built up as a string with newlines added manually, which seemed pretty clunky and not-streams-like to me.

In fact, you've been able to pass this as an array since PHP 5.2.10, so to set multiple headers in the stream context, I just used this:

<?php
$options = ["http" => [
    "method" => "POST",
    "header" => ["Authorization: token " . $access_token,
        "Content-Type: application/json"],
    "content" => $data
    ]];
$context = stream_context_create($options);

The $access_token had been set elsewhere (in fact I usually put credentials in a separate file and exclude it from source control in an effort not to spread my access credentials further than I mean to!), and $data is already encoded as JSON. For completeness, you can make the POST request like this:

<?php
// make the request
$response = file_get_contents($url, false, $context);

Hopefully this will help someone else doing the same thing next time (or at least I know I can come back here when I can't remember!), the array approach seems more elegant and maintainable to me.

4 thoughts on “Setting Multiple Headers in a PHP Stream Context

  1. That's a nice example! Have you also tested if it is possible to assign that by reference so that it is possible to change that array later without updating the context?

    • hakre, there are functions available to manipulate the params/options for any given stream or stream context. For example, [code]stream_context_set_option($context, ['http' => ['content' => 'hello, world']])[/code] could be used to change the request body.

  2. Code looks so clean using array format.
    How can we add Location header to this stream and there by change header options after redirect?
    Or, this context is only used for sending request to remote server using fopen(), file_get_contents() and etc.?

  3. Great info. Just remember that the [] notation for arrays was introduced with PHP 5.4.
    So, for the sake of older versions (since you mentioned PHP 5.2.10) maybe it's better to remind this or to use the old syntax array().

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>