This is a simple router written in PHP
add($method, $path, callback|string)
Adds a path to the router
addGet($path, callback|string)
Shorter version of add('GET', ...)
addBefore($method, $path, callback|string)
All before routes are processed first
addBeforeGet($path, callable|string)
Same as before, with 'GET' as default method
Router::buildURL($path)
BUild a printable URL for hrefs. For example: Router::buildURL('login') could return "/mysubdir/login"
The constructor needs the path to the controllers
$router = new Router(CONTROLLERS);
The add() functions doesn't need the leading '/' for the route
$router->addGet('', function() { echo 'Homepage!'; });
$router->addGet('test', function() { echo 'Test, first definition!<br>'; });
$router->addGet('test', function() { echo 'Test, second definition!<br>'; });
$router->addBefore('GET', '/admin/(.*)', function() use ($router) {
if (!empty($_SESSION['user_level']) && $_SESSION['user_level'] >= 2) {
# Logged in as admin
} else {
header('Location: ' . Router::buildURL('login'));
exit();
}
});
$router->addGet('admin/deleteUser/(\d+)', function($id) { echo "Delete user $id!"; });
$router->add('GET', 'admin/renameUser/(\d+)/(\w+)=(\w+)', function($id, $to, $from) { echo "Rename user $id from $from to $to!"; });
$router->add('GET', '/login', 'user@login');
$router->addGet('logout', 'user@logout');
$router->add404(function() { exit('404!'); });
$router->add('POST', 'api/showAllUsers', function() {
# Fake authentication
$auth = !empty($_SERVER['PHP_AUTH_USER']) && !empty($_SERVER['PHP_AUTH_PW']);
if ($auth) {
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
# Set up response
$users = [];
for ($i = 1; $i <= 10; $i++) {
$users[] = ['id' => $i, 'name' => 'Name' . $i];
}
exit(json_encode($users));
} else {
header('HTTP/1.0 403 Forbidden');
exit();
}
});
$router->add('POST', 'api/sendback', function() {
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
# Get posted data
$data = json_decode(file_get_contents('php://input'), true);
exit(json_encode(
array('response' => [
'send_data' => $data,
'auth' => [
'user' => !empty($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : 'unknown',
'pw' => !empty($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : 'unknown'
]
])
));
});
Finally you can start the router. It returns the amount of processed routes.
$numroutes = $router->start();