Swoole HTTP Response

4.x is outdated, please check the latest version 22.x

Latest version: pecl install openswoole-22.1.2

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:


A simple Open Swoole based SSE (server-sent events) example looks like this.

$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);

        $data = "event: ping\n";


        $curDate = date(DATE_ISO8601);

        $data = 'data: {"time": "' . $curDate . '"}';
        $data .= "\n\n";


           $data = 'data: This is a message at time ' . $curDate . "\n\n";



  • If a HTTP response has not been set, no message, no body data, then the server will simply send back $response->end('')
Last updated on September 16, 2022