CodShot
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);

Snippet actions

Pluto
Pluto
Updated: 2026-08-24 08:10
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support