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 = &#91;"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:



8 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().

  4. Just wanted to say thank you for this – I had almost exactly the same requirement when using a PUT request to send JSON to a server that also used an OAuth2 token in an Authorization header. Neat code.

  5. This is nice to know, thanks for sharing. Also remember that join() is great for tasks like this and is supported back to PHP 4. I use it frequently when needing to construct complex strings. Just set them up as arrays first then join them.

    [code]
    join(“\r\n”, $header);
    [/code]

    join() is an alias for implode() but the former is easier to remember (and type):
    http://php.net/manual/en/function.implode.php

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.