OpenSwoole\HTTP\Server->on('Request', fn)

Latest version: pecl install openswoole-22.1.2 | composer require openswoole/core:22.1.5

Declaration

<?php OpenSwoole\Server->on('Request', callable $callback)

Parameters

event

The event callback name.

callback

Callable function.

Return

success

If success, it returns true, otherwise it returns false.

Description

Execute the callback function when receiving a new incoming HTTP request, this is the first entry point where you run your main application logic for every request, compared to traditional PHP-FPM, you could say this event callback is your index.php file. But in this example we are taking advantage of the server event loop and its on Request event.

When running a HTTP server, you don't get access to the Connect or Receive events, instead you must use Request but the OpenSwoole HTTP server on method still acts the same.

This event is triggered when receiving a complete/whole HTTP request to the server, you will be passed two objects, OpenSwoole\Server\Request and OpenSwoole\Server\Response, you can use these objects to interact with the request and response of the server.

Upon this event's callback function exit or return, the given request and response objects will be destroyed, same with any class instances or variables that were created during the lifetime of this function, unless the callback type is an object defined elsewhere and no PHP closure was used.

Example

<?php
$server = new OpenSwoole\HTTP\Server("127.0.0.1", 9501);

$server->on('Request', function(OpenSwoole\Server\Request $request, OpenSwoole\Server\Response $response)
{
    $response->end('<h1>Hello World! Here is a random number: ' . rand(1, 1000) . '</h1>');
});

$server->start();

Request and Response Objects

Refer to the request and response documentation to learn more about them.

Last updated on September 20, 2022