Hello world
Create one route and the PHP controller it selects. This first response needs neither Composer nor a view class.
On this page
Before you begin
Use PHP 8.3–8.6 with either Nginx/PHP-FPM or Apache 2.4 with mod_rewrite and a PHP handler, configured for the project's web/ directory and chosen routing file as described in the environment prerequisites. No Composer autoloader or bootstrap is needed for this first example.
Replace the example URL http://my-app.test with your own.
Create two files
mkdir -p my-app/config my-app/web/GET
cd my-app
Choose one routing file for your server, then create the PHP controller below. Either choice needs only two application files.
File: config/nginx.conf
# Refuse direct script URLs before rewriting public paths.
if ($uri ~ "\.php(?:/|$)") {
return 404;
}
location / { return 404; }
set $handler_method $request_method;
if ($request_method = HEAD) {
set $handler_method GET;
}
rewrite ^/hello$ /$handler_method/hello.php last;
File: config/apache.conf
RewriteEngine On
RewriteRule \.php(?:/|$) - [R=404,L]
RewriteRule ^ - [E=handler_method:%{REQUEST_METHOD}]
RewriteCond %{REQUEST_METHOD} ^HEAD$
RewriteRule ^ - [E=handler_method:GET]
RewriteRule ^/hello$ /%{ENV:handler_method}/hello.php
RewriteCond %{DOCUMENT_ROOT}$0 -f
RewriteRule ^/.*\.php$ - [PT]
RewriteRule ^ - [R=404,L]
File: web/GET/hello.php
<?php
declare(strict_types=1);
echo "Hello world!";
The route sends GET /hello to web/GET/hello.php. The PHP file is the controller. No index.php dispatches the request, and no route table is loaded by PHP.
The selection variable copies the request method, mapping HEAD to the GET directory without changing the method received by PHP. POST would select web/POST/hello.php; because that file does not exist, the environment returns 404. The guard blocks incoming script URLs while allowing the server to select the script internally.
Try it
php -l web/GET/hello.php
curl -i http://my-app.test/hello
curl -i -X POST http://my-app.test/hello
curl -i http://my-app.test/GET/hello.php
Have the environment validate and reload the chosen server configuration before making these requests. Expect 200 with Hello world! for the first request and 404 for the others. PHP's normal HTML defaults supply the content type and UTF-8 charset.
Adding another action follows the same pattern: write its PHP file and add its rewrite. Read routing for parameters, or continue with a small application.