lamehacks

Stuff is fun

Simple PHP url dispatcher

PHP maps filenames into urls, this is a very handy feature and many applications simply use that for all their request handling needs. Practical as it can be, it’s quite limited.

Mapping url patterns into functions or Object methods is simple and easy. I’ll comment as I go…

//defining what url patterns get mapped into what funcitons.
//if no route is provided 'default' route is used
$routes = array(
	"default" => "sayhello",
	"hello" => "sayhello",
	"sum"  => "computesum"
);
 
/**
*Dispatch function - delegates action to other function and passes parameters to it
*/
function dispatch(){
 
	global $routes;
 
	//stear clear, allow only leters, numbers and slashes
	if(!empty($raw_route) and preg_match('/^[\p{L}\/\d]++$/uD', $_SERVER["PATH_INFO"]) == 0){
		die("Invalid URL");
	}
 
	//extract parameters
	$url_pieces = explode("/",$_SERVER["PATH_INFO"]);
	$action = $url_pieces[1];
	$params = array();
	if(count($url_pieces)>2){
		$params = array_slice($url_pieces, 2);
	}	
 
	//when no action is passed default action is performed
	if(empty($action)){
		$action="default";
	}
 
	//make sure the route is defined
	if(!in_array( $action, array_keys($routes))){
		die("Nothing to see here");
	}
 
	//all checked, execute requested funcion with provided parameters
	$action_function = $routes[$action];
	$action_function($params);
 
}
 
//just an example
function sayhello(){
	echo "Hello to you too!";
}
 
//another example
function computesum(){
	$params = func_get_arg(0);
 
	$sum = 0;
	$i=0;
	foreach($params as $par){
		$par = intval($par);
		$sum += $par;
		if ($i !=0){echo " + ".$par;}
		else{echo $par;}
		$i++;
	}
 
	echo " = " . $sum;
}
 
//run the whole thing
dispatch();

paste this into a file, for example dispatcher.php, put it on your server then try out urls like:

http://example.com/dispatcher.php/sum/1/2/3/4/10

http://example.com/dispatcher.php/hello

http://example.com/dispatcher.php

The file name can be removed if your server hasĀ supportĀ for url rewriting.

Related Posts:

Tags: , ,

4 Responses to “Simple PHP url dispatcher”

  1. white burberry bag Says:

    I am planing on getting the windows of my entire house tinted with a tint that blocks out 99% uv rays and 65% of heat. Will that qualify for a tax credit?

  2. JKK Says:

    NM/

  3. viagra Says:

    http://oxdvd.net/cat16-sub42.html

  4. Cheap Jordans Concords for Sale Says:

    The latest clash occurred in Hotan Prefecture, in the southern part of Xinjiang, whose population is predominantly Uighur. The Uighurs are a Turkic-speaking group sharing many affinities with people across Central Asia, and most follow relatively moderate forms of Sunni Islam. Many Uighurs resent the growing number of Han Chinese people, who have been attracted to Xinjiang by jobs in farming, energy production and mining.

Leave a Reply

. .

Entries (RSS) and Comments (RSS).