Skip to content

Instantly share code, notes, and snippets.

@webarthur
Last active October 3, 2016 16:35
Show Gist options
  • Select an option

  • Save webarthur/a0c53e9825210ff15e7c0c597588a8ee to your computer and use it in GitHub Desktop.

Select an option

Save webarthur/a0c53e9825210ff15e7c0c597588a8ee to your computer and use it in GitHub Desktop.
Small php router function
<?php
function routes($path, $routes) {
foreach ($routes as $route) {
// regular expressio to detect path tags
$tagsregex = '/(\{([\w]+)\})/';
// regular expression to test route
$regex = '/' . str_replace('/', '\\/', "^{$route[0]}$") . '/';
// get path variables
if(preg_match_all($tagsregex, $route[0], $vars)) {
$regex = preg_replace($tagsregex, '([^\/]+)', $regex);
}
// test route
if(preg_match($regex, $path, $matches)) {
// setup method and route function
if(is_string($route[1])) {
$method = $route[1];
$func = $route[2];
}
else {
$method = 'get';
$func = $route[1];
}
// test method
if(strtolower($_SERVER['REQUEST_METHOD'])===$method) {
// setup method and input data
if($method=='put' || $method=='delete') {
parse_str(file_get_contents("php://input"), $inputData);
}
elseif($method=='post') {
$inputData = $_POST;
}
elseif($method=='get') {
$inputData = $_GET;
}
// get path matches
if($vars) {
$path = [];
foreach($vars[2] as $k=>$var) {
$path[$var] = $matches[$k+1];
}
}
// call route function
call_user_func($func, $inputData, $path);
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment