Content · Web Development · PHP

Building a Basic PHP Router Without a Framework

A small router maps an HTTP method and exact path to a handler with a safe 404 fallback.

1 views Published Oct 17, 2026 Updated Oct 17, 2026 Admin

A small router maps an HTTP method and exact path to a handler with a safe 404 fallback.

What It Does and When to Use It


Match an exact method and path with a deliberate 404 fallback. Controllers translate HTTP input to operations; domain services implement rules; templates render escaped output.

Requirements, Inputs and Expected Behavior


Confirm the runtime, extension, environment variables, and permissions before running the examples in production. Decode and normalize paths carefully and do not treat unvalidated path strings as filenames.

Example 1: Basic Operation


Match an exact method and path with a deliberate 404 fallback.

<?php
$routes = ['GET /' => static fn () => 'Home', 'GET /health' => static fn () => 'OK'];
 $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
 $path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH);
 $handler = $routes[$method . ' ' . $path] ?? null;
 http_response_code($handler ? 200 : 404);
 echo $handler ? $handler() : 'Not Found';

Example 2: Behavior and Validation


Restrict dynamic route parameters before using their values.

<?php
$patterns = ['#^/posts/(?P<id>[1-9][0-9]*)$#D'];
 $path = '/posts/17';
 if (preg_match($patterns[0], $path, $matches)) echo (int)$matches['id'];

Practical Example: Application Use


Return a standards-aware method rejection without falling through to a different handler.

<?php
$allowed = ['GET', 'POST'];
 $method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
 if (!in_array($method, $allowed, true)) {
     http_response_code(405);
     header('Allow: GET, POST');
     exit;
 }
 echo 'Method accepted';

Important Behavior and Edge Cases


The second example highlights: Restrict dynamic route parameters before using their values. The practical example adds: Return a standards-aware method rejection without falling through to a different handler.

Comparison with Related Approaches


ApproachWhat changes
Controller, service and template responsibilitiesControllers translate HTTP input to operations; domain services implement rules; templates render escaped output.
Choosing safelyTreat template names, route parameters and user data as separate trust domains.

Common Beginner Mistakes


MistakeCorrect approach
Assuming successful execution proves the result is usableCheck the return value, required extension, and observable output of the specific operation.
Ignoring runtime and environment differencesVerify PHP version, SAPI, operating system, service access, and permissions before deployment.
Skipping operational constraintsDecode and normalize paths carefully and do not treat unvalidated path strings as filenames.

Key Takeaways


  • A small router maps an HTTP method and exact path to a handler with a safe 404 fallback.
  • Return a standards-aware method rejection without falling through to a different handler.
  • Treat template names, route parameters and user data as separate trust domains.
Share this resourceSend this page to someone who may find it useful.