Simple PHP router

Apache .htaccess (redirect all requests to not existing files/directories to index.php):

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]

PHP router file. Check if route is on list of available routes and include file by name of route. Some parts of route can be variables: ‘user/$name’. Variables can have default values: ‘users/$order=id’, default value can be empty string: ‘user/$name=’

<?php
var_dump((string)$_SERVER['REDIRECT_URL']);
$urlParts = explode('/', trim((string)$_SERVER['REDIRECT_URL'], '/'));

$routes = [
    'login',
    'logout',
    'user/$name',
    'users/list/$type=level/$page=2/$vocation=all',
];

function openRoute($pathParts, $vars)
{
    $file = 'pages/' . implode('_', $pathParts) . '.php';

    ob_start();
    extract($vars);
    $main_content = '';
    include($file);
    $main_content .= ob_get_clean();

    return $main_content;
}

$routeFound = false;

foreach ($routes as $route) {
    $routeParts = explode('/', $route);
    $vars = [];
    $pathParts = [];

    if (count($routeParts) >= count($urlParts)) {
        foreach ($routeParts as $partId => $routePart) {
            if ($routePart[0] === '$') {
                $optionalVar = strpos($routePart, '=') !== false;

                if ($optionalVar) {
                    list($varName, $defaultValue) = explode('=', $routePart);
                    $varName = substr($varName, 1);
                } else {
                    $varName = substr($routePart, 1);
                }

                if (isset($urlParts[$partId])) {
                    $vars[$varName] = $urlParts[$partId];
                } elseif ($optionalVar) {
                    $vars[$varName] = $defaultValue;
                } else {
                    continue 2;
                }
            } elseif (isset($urlParts[$partId]) && $routePart === $urlParts[$partId]) {
                $pathParts[] = $routePart;
            } else {
                continue 2;
            }
        }

        var_dump('found: ', $route, $vars, $pathParts);
        $main_content = openRoute($pathParts, $vars);
        $routeFound = true;

        break;
    }
}

if (!$routeFound) {
    http_response_code(404);
    echo '404 Not found';
    exit;
}

Leave a Reply

Your email address will not be published.