PHP
Public
Simple PHP Router with Dynamic User ID Route
This code implements a basic PHP router that directs static URLs to specific files and handles dynamic user ID routes, returning a 404 error for unmatched paths.
PHP
<?php
$routes = [
'/' => 'home.php',
'/about' => 'about.php',
'/user' => 'user.php'
];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
function handleRoute($uri, $routes)
{
if (array_key_exists($uri, $routes)) {
require $routes[$uri];
return;
}
// dynamic route example: /user/123
if (preg_match('#^/user/(\d+)$#', $uri, $matches)) {
$_GET['id'] = $matches[1];
require 'user-detail.php';
return;
}
http_response_code(404);
echo "404 - Page not found";
}
handleRoute($requestUri, $routes);