01.05.08

This is a very early version of what will become a class for dealing with url rewriting. I spent some time looking for url handling classes and while I found one I really like, it was just too much for what I needed in this case. Keep in mind the only thing this piece of code does right now is create an array. I’ve called this array $_PATH as it seemed to make sense considering its purpose and how it’s derived.

The .htaccess file is as follows:

Options +FollowSymLinks


	RewriteEngine on
	RewriteCond %{REQUEST_FILENAME} !-s
	Rewriterule (.*) index.php

This will take any request url and forward it to index.php leaving the URI intact. You can change index.php to anything you like and it does work in subdirectories.

<?php
 
// We need to the get the path to THIS file so we know where it's located.
$url_current_location = substr($_SERVER['PHP_SELF'], 0, strrpos($_SERVER['PHP_SELF'], "/")).'/';
 
// We also need the full URI from the address bar.
$url_full_uri = $_SERVER['REQUEST_URI'];
 
// By removing everything the path to THIS file from the full URI we are left with nothing but the our $_PATH variables.
$url_rewritten_uri = str_replace($url_current_location, '', $url_full_uri);
 
// If $_GET variables are set, remove them from $_PATH
if($_GET)
{
	$url_rewritten_uri = substr($url_rewritten_uri, 0, strrpos($url_rewritten_uri, "?"));
}
 
// Create the $_PATH array. Think of this is as simliar to a $_GET or $_POST array, but we're left with an array that contains our rewritten path.
$_PATH = explode('/', $url_rewritten_uri);
 
// Remove empty values caused by multiple or trailing slashes.
while(list($key, $value) = each($_PATH))
{
	if(empty($value))
	{
		unset($_PATH[$key]);
	}
}
 
// I want the total number of values in $_PATH so that later on I can easily find out how many segments are in the requested path.
$path_segment_count = count($_PATH);
 
// Now we'll add the segment count to $_PATH to make retreiving the segment count more convenient.
// In case there were multiple or trailing slashes in the URI, this will also reset the array keys to start at [0] and increment by 1.
$_PATH = array_merge(array($path_segment_count), $_PATH);
 
?>

Unless you’re comfortable with php this isn’t going to do you any good, however hopefully with some feedback it will shortly. You could use a hard-coded switch/case to call your files based on the URI or you could set up a table and a simple db structure for it. Either way I’m all ears for feedback and if you have any links to url rewriting classes that aren’t on phpclasses.org I’d appreciate a nudge.