Skip to content

Instantly share code, notes, and snippets.

@kensnyder

kensnyder/router.php

Created Apr 30, 2012
Embed
What would you like to do?
Create a rule for how a URL should be routed including the view name and the $_GET variables to set
<?php
function getViewPath($routes, $requestUri) {
// extract the path part of our url (e.g. '/news/3/1')
// and trim slashes
$url = trim( parse_url($requestUri, PHP_URL_PATH), '/');
if ($url == '') {
return 'views/home.php';
}
// get the values sent in the url
$parts = explode('/', $url);
// the first part is the view file name
$viewName = $parts[0];
$viewPath = "views/$viewName.php";
// make sure the path does not have a "http://" or ".."
// so we won't include a remote file or a file in a directory above
if (
strpos($viewPath, '://') !== false
|| strpos($viewPath, '..') !== false
|| !is_file($viewPath)
) {
return false;
}
// get the route we should use
$route = $routes[$viewName];
// ignore the first part, that was our view name
$varValues = array_slice($parts, 1);
$varNames = explode('/', $route);
// go through each var name in the route
foreach ($varNames as $i => $name) {
$_GET[$name] = $_REQUEST[$name] = @$varValues[$i];
}
return $viewPath;
}
// here define new routes
$routes = array(
'news' => 'id/page',
'contact' => 'action/id',
'blog' => 'year/month/day/post_id/post_name',
// ...
);
// get the view path. If false, send 404 otherwise include file
$viewFile = getViewPath($routes, $_SERVER['REQUEST_URI']);
if (!$viewFile) {
header('HTTP/1.0 404 Not Found');
die;
}
include($viewFile);
@kensnyder

This comment has been minimized.

Copy link
Owner Author

@kensnyder kensnyder commented Apr 30, 2012

Reference: http://forums.devnetwork.net/viewtopic.php?f=1&t=135475&p=676056

The $routes array has keys that represent the view file to use; it has values that represent the names of the variables to save to $_GET and $_REQUEST.

Example usage: getViewPath($routes, '/news/3/1'); returns "views/news.php" and sets $_GET['id'] = "3" and $_GET['page'] = "1".

Also, consider making a converse function that takes a view name and an associative array and returns a url. e.g. url('news', array('id'=>3, 'page'=>1)) would return "/news/3/1". That will reduce chance of error and allow you to change your routing scheme any time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment