Join 4,000+ others and never miss out on new tips, tutorials, and more.
4.x is outdated, please check the latest version 25.x
Latest version:
pecl install openswoole-25.2.0
The Swoole\HTTP\Response
object is passed to the Request
event when running a Swoole 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:
Swoole\Http\Response->header
Swoole\Http\Response->trailer
Swoole\Http\Response->cookie
Swoole\Http\Response->rawCookie
Swoole\Http\Response->status
Swoole\Http\Response->gzip
Swoole\Http\Response->redirect
Swoole\Http\Response->write
Swoole\Http\Response->sendfile
Swoole\Http\Response->end
Swoole\Http\Response->detach
Swoole\Http\Response::create
Swoole\Http\Response->goaway
Swoole\Http\Response->isWritable
A simple Open Swoole based SSE
(server-sent events) example looks like this.
<?php
$http->on('Request', function(Swoole\Http\Request $request, Swoole\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('')