6 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.

    join("\r\n", $header);

    join() is an alias for implode() but the former is easier to remember (and type):

Leave a Reply

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