Last active
August 29, 2015 14:28
-
-
Save zualex/d15474ea03cfe4b28535 to your computer and use it in GitHub Desktop.
Simple route in PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<?php | |
// Define routes | |
$routes = [ | |
'\/' => function() { return '<a href="/hello">Click here for a greeting</a>'; }, | |
'\/hello' => function() { return 'Hello world'; }, | |
'\/count\/(\d+)' => function($count) { return join("<br>", range(1,$count)); }, | |
'404' => function() { return 'Page not found'; } | |
]; | |
// Initialise the request, response and parameter list | |
$request = $_SERVER['REQUEST_URI']; | |
$response = false; | |
$parameters = array(); | |
// Find a route and define the response | |
foreach($routes as $route=>$action) { | |
if(preg_match('/^' . $route . '$/', $request, $matches)) { | |
// throw away the full match at the start of the array | |
$parameters = array_slice($matches,1); | |
$response = $action; | |
} | |
} | |
// If no route was found, use the 404 route as the response | |
if($response === false) { | |
$response = $routes['404']; | |
} | |
// Output the response | |
echo call_user_func_array($response, $parameters); | |
?> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment