A Friendly URL parsing function posted for review/reuse

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
Peter Anselmo
Forum Commoner
Posts: 58
Joined: Wed Feb 27, 2008 7:22 pm

A Friendly URL parsing function posted for review/reuse

Post by Peter Anselmo »

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.

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;
}
I'm using this and it works, but let me know if you see anything sloppy that could be improved :-)
User avatar
dude81
Forum Regular
Posts: 509
Joined: Mon Aug 29, 2005 6:26 am
Location: Pearls City

Re: A Friendly URL parsing function posted for review/reuse

Post by dude81 »

Use regular expressions for url parsing. You need not so many while loops
User avatar
Peter Anselmo
Forum Commoner
Posts: 58
Joined: Wed Feb 27, 2008 7:22 pm

Re: A Friendly URL parsing function posted for review/reuse

Post by Peter Anselmo »

Dude,
Thanks for the feedback. At most I could see a regular expression replacing only the second while loop. As the syntax is the same for folders and variables, I would think the directory check loop is necessary outside of regex.
Post Reply