Architecture

Build a Clean PHP Routing Layer

Create predictable routes, normalize paths and return appropriate HTTP responses in a custom PHP application.

Overview

Routing maps an HTTP method and URL path to an application action. A small routing layer prevents route matching from spreading across page scripts and makes URL behavior easier to test.

Normalize paths carefully

Parse the path from the request URI, decode only where appropriate, remove a trailing slash consistently and reject malformed paths. Do not treat arbitrary query-string content as part of the route. Match both the HTTP method and path; a POST request should not accidentally execute a GET-only action.

Prefer explicit route definitions

An explicit route table is easier to audit than a large collection of substring checks. Dynamic segments such as an article slug should be constrained to an expected pattern. Route parameters are still untrusted input and must be validated before use.

Handle HTTP methods and status codes

Return 404 when no route matches, 405 when the path exists but the method is unsupported, and 301 or 308 only when a permanent canonical redirect is intended. Use 302 or 307 for temporary redirects. Set response headers before output begins.

Security considerations

Never turn a URL segment directly into a PHP filename or include path. Avoid routes that expose internal file paths. For state-changing actions, require POST or another appropriate method, verify CSRF tokens and check authorization. GET requests should not change server state.

Testing routes

Test trailing slashes, URL-encoded characters, unknown paths, wrong methods, empty parameters and duplicate route definitions. Include canonical URL behavior in integration tests.

Official references

PHP parse_url HTTP Semantics – RFC 9110

Normalize the request before matching

Routing should compare a normalized path and an explicit HTTP method. Remove the query string from path matching, normalize trailing slashes consistently and reject malformed paths. Do not decode a path multiple times or allow encoded separators to bypass route checks.

<?php
$method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
$path = '/' . trim($path, '/');
if ($path !== '/') {
    $path .= '/';
}

$routes = [
    'GET /' => [HomeController::class, 'index'],
    'GET /contact/' => [PageController::class, 'contact'],
];

$key = $method . ' ' . $path;
if (!isset($routes[$key])) {
    http_response_code(404);
    require __DIR__ . '/../app/Views/errors/404.php';
    exit;
}

Treat this as a minimal illustration, not a complete router. A production router also needs parameter matching, method-not-allowed handling, safe parameter decoding and a clear policy for HEAD and OPTIONS.

Keep route definitions explicit

Use named routes or a central route table rather than embedding route checks in every page. Keep authorization separate from route matching: resolving a route does not mean the visitor is allowed to perform the action.

Define HTTP behavior

Return 404 for unknown paths, 405 when a known resource does not support the requested method, 301 or 308 for permanent canonicalization where appropriate, and 302 or 303 for temporary navigation flows. Avoid redirect loops and test both trailing-slash variants.

Test the route table

Cover duplicate route definitions, unknown paths, encoded characters, query strings, unsupported methods and route parameters. This keeps URL changes predictable as the application grows.