A Friendly URL parsing function posted for review/reuse
Posted: Tue Dec 09, 2008 3:32 pm
Hey All, I just spent a couple hours writing some code I thought I would pass on. I'm using a front-controller pattern to load in pages as called, and I needed a function to parse a friendly URL. My URLs are set up like so
http://www.mysite.com/page/key1/val1/key2/val2/
and it had to also work with folders
http://www.mysite.com/folder/page/key1/val1/key2/val2/
I searched around for a bit, and didn't find anything quite like I wanted. I also wanted it to fill the GET array like a normal, so the rest of the scripts wouldn't care how the URL was formed.
I'm using this and it works, but let me know if you see anything sloppy that could be improved 
http://www.mysite.com/page/key1/val1/key2/val2/
and it had to also work with folders
http://www.mysite.com/folder/page/key1/val1/key2/val2/
I searched around for a bit, and didn't find anything quite like I wanted. I also wanted it to fill the GET array like a normal, so the rest of the scripts wouldn't care how the URL was formed.
Code: Select all
function ParseFriendlyURL( $friendlyURL = $_SERVER['REQUEST_URI'] ) {
//divide the URL into parts to make modification easier
$splits = explode('/',trim($friendlyURL, '/'));
//if no page is specified, default to index
//otherwise, remove it from the array
$page = !empty($splits) ? array_shift( $splits ) : 'index';
//check if we're specifying directories
//if so update the page string to reflect the heirarchy
while( is_dir( $page ) ) {
if( empty( $splits ) ) {
$page .= '/index';
} else {
$page .= '/' . array_shift( $splits );
}
}
//if we have additional parameters, place them into the _GET array
while( !empty( $splits ) ) {
$_GET[array_shift($splits)] = array_shift($splits);
}
return $page;
}