Skip to content

Instantly share code, notes, and snippets.

@cisoun
Last active October 9, 2020 08:00
Show Gist options
  • Save cisoun/6c98e68cc196d2c2a6540b17588f13d2 to your computer and use it in GitHub Desktop.
Save cisoun/6c98e68cc196d2c2a6540b17588f13d2 to your computer and use it in GitHub Desktop.
PHP router
<?php
$uri = $_SERVER['REQUEST_URI'];
# Serve static ressources.
if (preg_match('/\.(?:png|jpg|jpeg|gif|css|js|svg)$/', $uri)) {
return false;
}
function register($method, $route, $callback) {
global $uri;
preg_match_all('/:([^\/]+)/', $route, $matches, PREG_SET_ORDER);
$pattern = preg_replace('/:[^\/]+/', '([^/]+)', $route);
$pattern = preg_replace('/\//', '\\/', $pattern);
$pattern = "/^$pattern\/?$/";
if ($method == $_SERVER['REQUEST_METHOD'] &&
preg_match_all($pattern, $uri, $matches, PREG_SET_ORDER)) {
$callback(...array_slice($matches[0], 1));
die();
}
}
function redirect($url) {
return function () use ($url) {
header('Location: ' . $url);
};
}
function view($path) {
return function () use ($path) {
require __DIR__ . $path . '.php';
};
}
register('GET', '/', view('/pages/index'));
register('GET', '/contact', view('/pages/contact'));
register('GET', '/photos', redirect('/photos/2020'));
register('GET', '/photos/:year', function ($year) {
require __DIR__ . '/photos/index.php';
});
die('404');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment