by

Hooking routes.php in CodeIgniter to Create User-Based Personal Short URL Alias

Suppose you are stuck in the middle of a case where you are challenged to create a website with thousands or millions of members. Each member may have a personal URL alias, like:
http://www.example.com/yourname

In CodeIgniter you could solved this problem by configuring the routes.php file in the application/config directory. But, the problem is, how if you have millions of user's personal URL in your web application?

Well, this problem came up to me a few months ago when i was assigned on a mission to create a medium scale social networking site.

The idea is creating a controller to handle the user-related operations. In the controllers, create a function called view, which process the user viewings operation.

So we could call something like this when viewing a user profile:
http://www.example.com/user/view/SHORT_URL_ALIAS

Then hook the routes.php file, by detecting the uri segments. So if someone request something like this:
http://www.example.com/YOURNAME

It was actually redirected to:
http//www.example.com/user/view/YOURNAME

Note: the examples below was written in CodeIgniter version 1.7.2

Create the user.php controller

File: application/controllers/user.php

class User extends Controller {

	function User ()
	{
		parent::Controller();
	}


	// lets view user profile with this method
	function view ($short_url)
	{
		// search the user with given short url
		$query = $this->db->query (
			"SELECT * FROM users WHERE short_url='{$short_url}'"
		);

		if ($query->num_rows ())
		{
			// ok, we found users with that short_url
			// display it
			// do your own code here
		}
		else
		{
			echo 'No users with that id';
			exit;
		}
	}
}

Let's mess up with the routes.php file

Open the routes.php in application/config/ directory.
Then insert this code:

    // create a function to get the controller's listing
    // so we could exclude it from the url alias
    function __get_reserved_uri ($directory)
    {
        $results = array();
        $handler = opendir ($directory);
    
        // open directory and walk through the filenames
        while ($file = readdir($handler))
        {
            // if file isn't this directory or its parent, add it to the results
            if ($file != "." && $file != "..")
            {
                $results[] = basename ($file, ".php");
            }
        }
    
        // tidy up: close the handler
        closedir ($handler);
    
        // create a handler for the directory
        $handler = opendir (FCPATH);
    
        // open directory and walk through the filenames
        while ($file = readdir($handler))
        {
            // if file isn't this directory or its parent, add it to the results
            if ($file != "." && $file != "..")
            {
                $results[] = basename ($file);
            }
        }
    
        // tidy up: close the handler
        closedir ($handler);
    
        // done!
        return $results;
    }
    
    
    $controllers_dir = "./application/controllers/";
    
    // break the uri manually
    // notes: this is for $config['uri_protocol'] = 'PATH_INFO;
    // 		 if you modify the variables above in config.php
    //		 you have to modify the lines below
    $path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
    $uri = explode ("/", $path);
    // end uri config
    
    
    if ( count ($uri) == 2 && ! in_array ($uri[1], __get_reserved_uri ($controllers_dir)))
    {
        $route[$uri[1]] = "user/view/{$uri[1]}";
    }

It works for me, hope it works for you too.

phptipscodeigniterrouting