[eluser]daparky[/eluser]
Vanity URL's are best described as a personalised URL, for example if you want to create a website where a user has their own space, e.g. example.com/username. Companies use this method to advertise a specific product as it's easy to remember and more to the point.
I decided to give the a whirl in Codeigniter which out of the box does not allow this to happen because of the MVC pattern.
If you want vanity url's in Codeigniter you have a couple of choices. They both involve URI Routing if you open that file (application/config/routes.php) and paste the following code in:
Code:
// if you are using modules
if($handle = opendir(APPPATH.'/modules'))
{
while(false !== ($module = readdir($handle)))
{
if($module != '.' && $module != '..')
{
$route[$module] = $module;
$route[$module.'/(:any)'] = $module.'/$1';
}
}
closedir($handle);
}
// if you are using standard MVC
if($handle = opendir(APPPATH.'/controllers'))
{
while(false !== ($controller = readdir($handle)))
{
if($controller != '.' && $controller != '..' && strstr($controller, '.') == '.php')
{
$route[strstr($controller, '.', true)] = strstr($controller, '.', true);
$route[strstr($controller, '.', true).'/(:any)'] = strstr($controller, '.', true).'/$1';
}
}
closedir($handle);
}
// these are the /username routes
$route['([a-zA-Z0-9_-]+)'] = 'controller/index/$1';
$route['([a-zA-Z0-9_-]+)/subpage'] = 'controller/subpage/$1';
Then in a controller you would have:
Code:
function index($username = '')
{
echo $username;
}
function subpage($username = '')
{
echo $username.' subpage';
}
The other method is very similar, just a different way of achieving it in URI Routing:
Code:
// modules
if($handle = opendir(APPPATH.'/modules'))
{
while(false !== ($module = readdir($handle)))
{
if($module != '.' && $module != '..')
{
$controllers[] = $module;
}
}
closedir($handle);
}
// controllers
if($handle = opendir(APPPATH.'/controllers'))
{
while(false !== ($controller = readdir($handle)))
{
if($controller != '.' && $controller != '..' && strstr($controller, '.') == '.php')
{
$controllers[] = strstr($controller, '.', true);
}
}
closedir($handle);
}
$url_parts = explode('/',$_SERVER['REQUEST_URI']);
$reserved_routes = $controllers;
// these are the /username routes
if( ! in_array($url_parts[1], $reserved_routes))
{
$route['([a-zA-Z0-9_-]+)'] = 'controller/index/$1';
$route['([a-zA-Z0-9_-]+)/subpage'] = 'controller/subpage/$1';
}
Obviously if you aren't using modules you can remove the modules code and vice versa.
Hope it helps.
Codeigniter Vanity URL's