Personalized User Vanity Url’s in Codeigniter

This may seem an obvious solution, but after doing some digging, i didn’t find anyone else writing about it.

What I tried to accomplish was personalized urls like http://www.site.com/philpalmieri.  First i tried to use a pre_controller hook, but the url was being interpreted to quickly…  So i came up with a simple solution – hopefully it can help someone else out.

First step is to create an ‘aliases’ controller (and module if you are using them)..  Create a method in the aliases controller – something like check()… This is what we will be passing the personalized url to to figure out what to do.

How this works is that we check for any modules or controllers that would normally be called in uri->segment(1).  Then, dynamically account for each one in your routes file….  finally, we route everything else to aliases/create/*

So.   for the code

add & customize the following to your routes file (before any other custom routes).

$handle = opendir(APPPATH."/modules");
while (false !== ($file = readdir($handle))) {
  if(is_dir(APPPATH."/modules/".$file)){
    $route[$file] = $file;
    $route[$file."/(.*)"] = $file."/$1";
  }
}

/*Your custom routes here*/

/*Wrap up, anything that isnt accounted for pushes to the alias check*/
$route['([a-z-_/]+)'] = "aliases/check/$1";
Be Sociable, Share!

5 Comments

  • July 15, 2010 - 10:53 pm | Permalink

    Thanks so much for this. Really helped me make URI’s world’s easier for my users.

    • July 16, 2010 - 6:04 am | Permalink

      Thanks for reading! glad you found it useful.

  • July 16, 2010 - 1:29 pm | Permalink

    I did have some trouble getting the automatic routing conditions working. Since I only have 5 controllers I just wrote out the 10 statements that I needed.

  • October 28, 2011 - 7:35 am | Permalink

    Hi I’m using HMVC to structure my app would I have to place this in the main rout or in all the routes in the respective modules.

    Also what code would I have to add in the ‘aliases’ controller (and module if you are using them)

    • October 28, 2011 - 8:51 am | Permalink

      Hi @oudin,

      I’m using HMVC with it too.. I place it in the /app/config/routes.php

      So: $route['(:any)'] = “aliases/check/$1″;

      in my aliases controller, i basically take the uri->segment(3) and check against the users/item table for the alias.

  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    * Copy This Password *

    * Type Or Paste Password Here *

    You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>