Join 4,000+ others and never miss out on new tips, tutorials, and more.
Latest version:
pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5
<?php OpenSwoole\Http\Response->header(string $key, string $value, bool $format = true)
The key of HTTP header
The value of HTTP header
If true, the header key will be automatically formatted to fit HTTP naming requirements
No value is returned
If setting the header fails, then false
will be returned
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. OpenSwoole 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.
<?php
$server->on('Request', function(OpenSwoole\Server\Request $request, OpenSwoole\Server\Response $response)
{
$response->header('Content-Length', '100002 ');
$response->header('Content-Type', 'image/jpeg');
});
Since v4.6.0
you can use a range of PHP types (array, object, int, float) to set the HTTP header, OpenSwoole 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(OpenSwoole\Server\Request $request, OpenSwoole\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'));
});