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
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.
php server.php m4w.jsonWith 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.
php server.phpSend a request
In a second terminal, send a request to the loopback listener.
curl -i http://127.0.0.1:9000/helloThe response is HTTP 200 with a JSON body.
{"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.
curl -i -H 'Content-Type: text/plain' --data-binary 'Hello again' http://127.0.0.1:9000/echo{"echo": "Hello again"}Try GET /missing for a 404. Press Ctrl+C in the server terminal when you are done.