First run

Write a handler

Save this as server.php next to vendor/. Mini4Work calls the handler for each request and sends the response it returns.

PHP
<?php

use M4W\WebServer\Cli\ServerCommand;
use M4W\WebServer\Http\CallbackRequestHandler;
use M4W\WebServer\Http\Request;
use M4W\WebServer\Http\Response;

require __DIR__.'/vendor/autoload.php';

$handler = new CallbackRequestHandler(static function (Request $request): Response {
    $path = explode('?', $request->uri, 2)[0];

    if ($request->method === 'GET' && $path === '/hello') {
        return Response::json(['message' => 'Hello from PHP!']);
    }

    if ($request->method === 'POST' && $path === '/echo') {
        $text = $request->body->readAll(65536);
        return Response::json(['echo' => $text]);
    }

    return Response::text("Not found\n", 404);
});

exit((new ServerCommand)->run($argv, $handler));

Start the server

Use the port 9000 profile from Basic configuration. Restart the process after editing the PHP file.

Shell
php server.php m4w.json

With the two-worker profile, the server.listening log entry shows "workers":2 and "connections_per_worker":16. Restart the server after editing the file.

Run with the defaults

Without a profile, the server listens on 127.0.0.1:8080. Use port 8080 for the request below.

Shell
php server.php

Send a request

In a second terminal, send a request to the loopback listener.

Shell
curl -i http://127.0.0.1:9000/hello

The response is HTTP 200 with a JSON body.

JSON
{"message": "Hello from PHP!"}

Send plain text to /echo. The handler reads up to 64 KiB from the request body and returns the text in JSON.

Shell
curl -i -H 'Content-Type: text/plain' --data-binary 'Hello again' http://127.0.0.1:9000/echo
JSON
{"echo": "Hello again"}

Try GET /missing for a 404. Press Ctrl+C in the server terminal when you are done.