Content · Web Development · PHP

Building Basic URL Routing in PHP

A plain PHP router matches HTTP methods and paths to handlers for clean navigation. Parsing route parameters does not authenticate or authorize them; normalize URL paths.

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

A plain PHP router matches HTTP methods and paths to handlers for clean navigation.

What It Does


A plain PHP router matches HTTP methods and paths to handlers for clean navigation. The following examples distinguish a normal use case, a boundary case and a practical application.

Requirements and Compatibility


PHP 8.x and a local test environment. Apply input validation, correct error handling and the requirements of any optional libraries.

The code focuses on the core concept. Production implementation may also need routes, validation, persistence, authorization or deployment tooling.

Example 1: Basic Behavior


Understand the primary operation and its inputs.

<?php
$routes = ['GET /items' => fn () => 'list', 'POST /items' => fn () => 'create'];
$key = 'GET /items';
echo isset($routes[$key]) ? $routes[$key]() : '404';

Example 2: Another Case


Check failure behavior or a different execution path.

<?php
$path = parse_url('/items/17?view=short', PHP_URL_PATH);
if (preg_match('~^/items/(?P<id>\d+)$~D', $path, $m)) echo (int) $m['id'];

Practical Example: Putting It to Use


Apply the behavior in a small, controlled scenario.

<?php
function controller(array $request): array { return ['status' => 200, 'body' => ['method' => $request['method']]]; }
echo json_encode(controller(['method' => 'GET']), JSON_THROW_ON_ERROR); // Render the response separately

Important Behavior and Edge Cases


Parsing route parameters does not authenticate or authorize them; normalize URL paths carefully.

Comparison with Related Functions or Approaches


OptionWhat it means in practice
Building Basic URL Routing in PHPA plain PHP router matches HTTP methods and paths to handlers for clean navigation.
Related approachA front controller dispatches all requests through one entry point.

Common Beginner Mistakes


MistakeCorrect approach
Ignoring the important boundary for Building Basic URL Routing in PHPParsing route parameters does not authenticate or authorize them; normalize URL paths carefully.
Assuming a related mechanism has the same behaviorA front controller dispatches all requests through one entry point.

Key Takeaways


  • A plain PHP router matches HTTP methods and paths to handlers for clean navigation.
  • Parsing route parameters does not authenticate or authorize them; normalize URL paths carefully.
  • A front controller dispatches all requests through one entry point.

Before adapting these examples, verify the return values, test the failure paths and confirm that your application meets its security and environment requirements.

Share this resourceSend this page to someone who may find it useful.