Nice URLs and PHP

I all one for nice url’s, that is removing all the gumf involving question marks and ampersands and the like for something that is both shorter, more human readable and more search engine friendly.

Doing it in PHP is actually pretty straightforward once you get the hang of it and can be pretty powerful – so here goes with a short tutorial of sorts. It’s will probably be brief and make too many assumptions of the reader – any questions just let me know and I may even try and write it up properly.

The basic principle is to stop using the GET array (accessible from $\_SERVER\[‘GET’\]) to make descisions with. The question then becomes what to replace it with. A simple class borrowed from the Sitepoint PHP Anthology book written by Harry Fuecks is at least my answer. The PathVars class does pretty much what is says in the name, specifically providing access to the path contents in the form of an array. I’ll provide a link to a code archive for this article rather than just copy and paste whole classes – download it now if you are interested in the behind the scenes bits.

So we now create a new PathVars instance like so:

/* Pathvars object */ $pathvars = new PathVars($_SERVER['SCRIPT_NAME']);

And we can now magically get access to each element of the path (separated by a /) from the instance variable pathvars:

$params = $pathvars->pathVars;

Or more correctly by using the method provided:

$pathvars->fetchByIndex(0)

Where the fetchByIndex parameter is the element you want from the array.

Ok, so so far I’m really just repeating the work of others, if you like this sort of thing I’d really recommend the book. The next step on top of this is however is to decide what to do with the information when you have it. The following shows a very simple example – potentially for use in a simple blog or news site:

switch ($pathvars->fetchByIndex(0)) { case "article": include(views/article.view.php); case "page": include(views/page.view.php); default: include('views/home.view.php'); }

In this example where we have www.example.com/article or www.example.com/article/a\_sample\_article\_name the article view include file is used.

What these include files then do is up to you, in my case each of them passes different parameters to a simple templating system which then outputs the page. Again, have a look at the code samples to see that in action.

Let me know if anyone found this interesting, useful or informative and I might post other titbits, otherwise it’s probably back to inane ramblings and misplaced conjecture.