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
The OpenSwoole\HTTP\Response
object is passed to the Request
event when running a OpenSwoole HTTP server and allows you to build a HTTP server response to the client, this object allows you to setup a response based on the current request and send data back to the client. You can set things like the headers, HTTP status, cookies, body data and files etc. This object is responsible for how the client will receive the server response.
You should not access this object via call-by-reference (use of the &
symbol in PHP) because the object is destroyed afterwards and may lead to undefined object errors, only access it from the event callback, this object is only valid during the lifecycle of the server request, meaning the response object is destroyed after the request has finished.
You can use the following methods to create and form a HTTP server response which gets sent to the client:
OpenSwoole\Http\Response->header
OpenSwoole\Http\Response->trailer
OpenSwoole\Http\Response->cookie
OpenSwoole\Http\Response->rawCookie
OpenSwoole\Http\Response->status
OpenSwoole\Http\Response->gzip
OpenSwoole\Http\Response->redirect
OpenSwoole\Http\Response->write
OpenSwoole\Http\Response->sendfile
OpenSwoole\Http\Response->end
OpenSwoole\Http\Response->detach
OpenSwoole\Http\Response::create
OpenSwoole\Http\Response->goaway
OpenSwoole\Http\Response->isWritable
A simple Open Swoole based SSE
(server-sent events) example looks like this.
<?php
$http->on('Request', function(OpenSwoole\Http\Request $request, OpenSwoole\Http\Response $response)
{
$response->header('Content-Type', 'text/event-stream');
$response->header('Cache-Control', 'no-cache');
$counter = rand(1, 10);
while(true)
{
$data = "event: ping\n";
$response->write($data);
$curDate = date(DATE_ISO8601);
$data = 'data: {"time": "' . $curDate . '"}';
$data .= "\n\n";
$response->write($data);
$counter--;
if(!$counter)
{
$data = 'data: This is a message at time ' . $curDate . "\n\n";
$response->end($data);
break;
}
co::sleep(1);
}
});
$response->end('')