varemenos
5/15/2013 - 3:38 AM

PHP - Basic URL Routing

PHP - Basic URL Routing

<?php
	if(!empty($_REQUEST)){
		// get real parameters
		$parameters = $_REQUEST;
	}

	if(isset($_SERVER['PATH_INFO'])){
		// path = the trimmed PATH_INFO string
		// allowed characters:
		// {'a','b',..,'z'},{'A','B',...,'Z'},{'0','1',...,'9'},{'_','/','.'}
		// every other character will be replaced with an empty string
		$temp = $_SERVER['PATH_INFO'];
		$path = preg_replace('/[^a-zA-Z0-9_\/.]/', '', strtolower($_SERVER['PATH_INFO']));

		// check if inserted url and cleaned url are the same
		if($temp != $path){
			// if they are not then print an error message
			echo '<span class="warning">please make sure the current link is correct. Some characters were omitted.
			<br>From "'.$temp.'" to "'.$path.'".</span>';
		}

		// explode the path string into an array of commands
		$commands = explode('/', $path);
		// calculate the amount of commands
		$amount_of_commands = count($commands);
		for ($i=0; $i < $amount_of_commands; $i++) {
			// if current command is an empty string
			if($commands[$i] == '' || $commands[$i] == 'index.php'){
				// then remove it
				unset($commands[$i]);
			}
		}
		// reset the array keys
		$commands = array_values($commands);
		// var_dump($commands);
	}

	// initialize type object
	$type->name = null;
	$type->id = 0;
?>