Skip to content
Tutorials Center
My learning

Topics

Lesson 80 of 147 ยท PHP and the Web

Front Controllers and Routing

Send every request through one index.php: parse the URL path, build a tiny PHP router with closures and route parameters, handle 404 and 405, and set up pretty URLs.

The simplest way to build a PHP site is one file per page: about.php, contact.php, product.php?id=42. The web server maps each URL straight to a file, and that works fine for five pages. At fifty, it starts to hurt. Every file repeats the same setup (sessions, database connection, error handling, security headers), URLs expose your file layout, and nice addresses like /products/42 are impossible without extra tricks.

Almost every modern PHP application solves this with a front controller: a single index.php that receives every request. It runs the shared setup once, looks at the requested URL, and hands the request to the right piece of code. That last step, mapping a method and a URL to a handler, is called routing, and the code that does it is a router.

In this lesson you'll set up a front controller, parse request URLs safely, and build a small but real router with closures, route parameters, 404 Not Found and 405 Method Not Allowed. It's the same idea that the routers in Laravel, Symfony and Slim are built on.

From many files to one entry point

Here's the layout of a typical front-controller project. Only the public folder is reachable from the web; everything else lives outside it:

TEXT
my-app/
โ”œโ”€โ”€ public/              <- the web server's document root
โ”‚   โ”œโ”€โ”€ index.php        <- the front controller: every request starts here
โ”‚   โ”œโ”€โ”€ css/app.css      <- static files are served directly
โ”‚   โ””โ”€โ”€ images/logo.svg
โ”œโ”€โ”€ src/                 <- your classes: controllers, models, services
โ”œโ”€โ”€ templates/           <- view files
โ”œโ”€โ”€ config/
โ””โ”€โ”€ vendor/              <- Composer packages

Keeping code outside the document root is a real security win: even if the server is misconfigured and serves .php files as plain text, your configuration, database passwords and source code can't be downloaded, because no URL points to them.

The front controller itself is short. It loads the app, builds a router and dispatches the current request:

PHP
<?php
// public/index.php
declare(strict_types=1);

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

session_start();
header('X-Content-Type-Options: nosniff');

$router = require __DIR__ . '/../config/routes.php';

$router->dispatch($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

Autoloading (the require of vendor/autoload.php) is covered in Autoloading and Composer.

Pretty URLs: sending every request to index.php

The web server must be told: "if the request is for a file that exists (a CSS file, an image), serve it; otherwise run index.php". With nginx, that's the try_files line:

NGINX
server {
    listen 80;
    server_name example.test;
    root /var/www/my-app/public;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        fastcgi_pass unix:/run/php/php8.5-fpm.sock;
    }
}

With Apache, mod_rewrite rules in public/.htaccess do the same:

TEXT
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [L]

For local development, PHP's built-in server accepts a router script as its last argument. It runs index.php for every request that isn't a real file:

Terminal
php -S localhost:8000 -t public public/index.php

Either way, inside index.php the original URL is still available in $_SERVER['REQUEST_URI'], and the HTTP method in $_SERVER['REQUEST_METHOD'] (see Superglobals).

Parsing the request path

REQUEST_URI is the raw path plus query string exactly as the browser sent it, for example /blog/hello%20world?page=2. Before matching it against routes, you need just the path, decoded, in a consistent shape. Our editor has no web server, so this demo sets up a few simulated REQUEST_URI values and runs them through a normalizing function:

PHP Extracting a clean path from REQUEST_URI

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Splitting at the first ? drops the query string, rawurldecode() turns %20 back into a space, and trimming slashes means /blog and /blog/ reach the same route.

You'll often see parse_url($uri, PHP_URL_PATH) used for the first step, and it works for normal paths. But parse_url() parses full URLs, so it reads a path that starts with // as a host name: parse_url('//admin///users', PHP_URL_PATH) returns '///users', losing the admin segment. Since REQUEST_URI is always a path (never a full URL), splitting at ? is both simpler and safer. Some sites prefer to redirect /blog/ to /blog with a 301 instead, so search engines see only one URL per page (redirects are covered in the previous lesson). On a real server you don't need parse_str(): PHP has already filled $_GET from the query string.

A first router: an array of closures

The simplest router is an array that maps a method and a path to a function. Anonymous functions make perfect route handlers:

PHP Exact-match routing with an array

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Looking up $routes[$method][$path] is a hash lookup, so it's fast no matter how many routes you add. The ?? operator returns null for an unknown path, which becomes a 404. Real handlers would render a template or produce JSON, and the front controller would turn [$status, $body] into http_response_code($status); echo $body;.

This router has two weaknesses: it can't match URLs that contain values, like /products/42, and it answers 404 for DELETE /contact, although that URL exists. Let's fix both.

Route parameters with regular expressions

Routes like /products/{id} contain placeholders. The router turns each pattern into a regular expression with a named group per placeholder, so /products/{id} becomes #^/products/(?<id>[^/]+)$#. Matching the path then captures the values by name.

We'll also distinguish two kinds of failure:

  • 404 Not Found: no route matches the path at all.
  • 405 Method Not Allowed: the path matches, but not with this method. HTTP requires an Allow header listing the methods that would work.
PHP A router with parameters, 404 and 405

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A few details are worth a closer look:

  • preg_quote() escapes characters that mean something in a regex, so the dot in /feed.xml matches only a literal dot. Without it, /feedXxml would match too. Because preg_quote() also escapes { and }, the placeholder pattern looks for \{name\}, which is why it contains so many backslashes.
  • [^/]+ means "one or more characters that aren't a slash", so a parameter never swallows the next path segment. /products/42/reviews doesn't match /products/{id}.
  • array_filter(..., ARRAY_FILTER_USE_KEY) keeps only the string keys from $matches (the named groups), and $handler(...$params) passes them as named arguments (PHP 8.1+), so the order of parameters in the closure doesn't matter. Parameters and Arguments explains spreading arrays with string keys.

Route parameters arrive as strings. If a handler needs an integer, validate it (ctype_digit($id)) or tighten the regex. Many routers let you write constraints such as {id:\d+}; adding that to our router is a good exercise.

Handlers that produce real responses

Real handlers need to read input, choose a status code and escape output. Here the handlers receive a small Request object and return a Response, and a missing product becomes a 404 from inside the handler. The request data is simulated, as in the other demos:

PHP Requests, responses and escaping in handlers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The output is HTML source shown as text; a browser would render the headings. Notice the search result: the <script> tag from the simulated query string comes out as harmless &lt;script&gt;. Every value from the URL is user input, including route parameters, so it's escaped before it reaches HTML (Preventing XSS). Also notice that /products/abc gives a clean 404 instead of an error, because the handler validates the parameter.

This version keeps routes in a plain array for brevity, so it compiles the regex on every request. Production routers compile all routes once (often into one combined regex) and cache the result, so dispatch stays fast with hundreds of routes.

Controllers instead of closures

Closures are great for a handful of routes, but large apps group related handlers into controller classes. A route then points to a class and method, and the router creates the controller and calls the method:

PHP Routing to controller methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

[ArticleController::class, 'show'] is the standard way to name a method without calling it, and new $class() creates an object from a class name stored in a variable. In a framework, a dependency injection container builds the controller instead, passing in the database connection and other services it needs (OOP Design Principles explains why, and Reflection shows how containers do it).

What real routers add

Once the basics work, frameworks layer more on top. Knowing the names helps you read their documentation:

  • Named routes and URL generation: route('product.show', ['id' => 42]) builds /products/42, so changing a URL means editing one line.
  • Middleware: functions that run before or after the handler (authentication, CSRF checks, rate limiting, adding headers). Each one can stop the request early, for example with a redirect to the login page.
  • Route groups: a common prefix (/admin) and middleware for many routes at once.
  • Constraints and model binding: must be digits, and the framework loads the matching database record for you.
  • Route caching: all routes compiled once at deploy time.

For example, here's how Slim, a small framework, writes the same product route:

PHP
$app->get('/products/{id}', function ($request, $response, array $args) {
    $response->getBody()->write('Product #' . $args['id']);
    return $response;
});

The shape is the same as in your router: a method, a pattern, and a handler that receives the parameters. PHP Frameworks and CMSs compares the popular options.

Avoid building routes from file names, as in include $_GET['page'] . '.php';. It looks like a quick router, but it lets attackers include files you never meant to expose (path traversal and file inclusion, covered in Secure Coding Checklist). A router with an explicit list of routes only runs code you registered.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a front controller?

    All requests go through one entry point that runs shared setup and passes the request to the right handler.
  2. 2. Using the lesson's requestPath() function, what does requestPath('/blog/hello%20world/?page=2') return?

    The query string is dropped at the ?, rawurldecode() turns %20 into a space, and the trailing slash is trimmed.
  3. 3. The path /products/42 exists for GET, but the client sends DELETE /products/42. What should a correct router answer?

    The resource exists but doesn't support that method, so the right answer is 405 with an Allow header listing the supported methods.
  4. 4. Why does the router call preg_quote() on the route pattern before adding the placeholder groups?

    In a regex, an unescaped dot matches any character, so /feed.xml would also match /feedXxml. preg_quote() escapes such characters.
  5. 5. In nginx, which directive sends requests for non-existent files to index.php?

    try_files serves the file or directory if it exists and falls back to the front controller otherwise.

Summary

  • A front controller (public/index.php) receives every request, runs shared setup once and dispatches to a handler. Keep everything except public assets outside the document root.
  • Configure the web server to fall back to index.php: try_files in nginx, mod_rewrite in Apache, or php -S localhost:8000 -t public public/index.php locally.
  • Get a clean path from $_SERVER['REQUEST_URI'] by dropping the query string, calling rawurldecode() and trimming slashes; the method is in $_SERVER['REQUEST_METHOD'].
  • A router maps method + path to a handler. Exact paths fit in an array; patterns like /products/{id} become regexes with named groups (escape literal parts with preg_quote()).
  • Answer 404 when no path matches and 405 with an Allow header when only the method is wrong. Route parameters are user input: validate and escape them.
  • Controllers group handlers into classes; real routers add named routes, middleware, groups, constraints and caching.

Next: Building a JSON API