PHPPHP19 min read

Simple Router in PHP (Clean URLs, Controller Style)

Create a simple routing system so you can build /users/1 instead of messy query strings.

Emma Hughes
September 27, 2025
5.5k156

Routing means mapping URL paths to code.

Instead of:

  • user.php?id=5

You can do:

  • /users/5

Step 1: Front controller idea

All requests go to index.php, then routing decides what to run.

Step 2: Very simple route matching

<?php
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'GET' && $path === '/') {
  echo "Home";
  exit;
}

if ($method === 'GET' && preg_match('#^/users/(\d+)$#', $path, $m)) {
  $id = (int)$m[1];
  echo "User page for id " . $id;
  exit;
}

http_response_code(404);
echo "Not found";
?>

Why this matters

This is the foundation of frameworks. Once you get routing, MVC becomes much easier.

Next: Dependency Injection concept in PHP (simple and practical).

#PHP#Architecture#Advanced