Swoole\Http\Response->header

Notice: the documentation is suitable for PHP extension swoole until v4.7.1, we only support PHP extension openswoole from v4.7.1

Declaration

<?php
Swoole\Http\Response->header(string $key, string $value, bool $format = true)

Parameters

key

The key of HTTP header

value

The value of HTTP header

format

If true, the header key will be automatically formatted to fit HTTP naming requirements

Return

successful

No value is returned

fails

If setting the header fails, then false will be returned

Description

Set a HTTP header which will be sent to HTTP client.

The header key must fully comply with the HTTP protocol, each word must be capitalized and only use - for word separation, no underscores or other special characters. A header value must always be given. Swoole can automatically format the header key for you with $format = true (default) but it is recommended that you set keys with respect to the HTTP standard.

Repeating the same key more than once will just overwrite any previously set value before the response is sent back to the client.

This method must be called before the $response->end method.

Example

General Usage

<?php

$server->on('Request', function(Swoole/Server/Request $request, Swoole/Server/Response $response)
{
  $response->header('Content-Length', '100002 ');
  $response->header('Content-Type', 'image/jpeg');
});

Advanced Usage

Since v4.6.0 you can use a range of PHP types (array, object, int, float) to set the HTTP header, Swoole will then convert them into their string representation and use that as the header value. Let's have a look at an array and an object example:

<?php

$server->on('Request', function(Swoole/Server/Request $request, Swoole/Server/Response $response)
{
  // Each element will be converted to a string and set as the value, end spaces and line breaks are removed
  $response->header('Test-Value', [
    "a\r\n",
    'd5678',
    "e  \n ",
    null,
    5678,
    3.1415926,
  ]);

  // toString() will be used to convert this object to a string value
  $response->header('Foo', new SplFileInfo('bar'));
});