Thursday, March 22, 2012

codeigniter routing issue fixation - url rewriting issue fixation.

I have a problem with codeigniter url rewriting.

I have to go to www.abc.com/catalog/product/4354

when using the url www.abc.com/samsung_galaxy_y

As per the documentation I have added it in the routes.php page in application/config folder.

$route['default_controller'] = "index";
$route['404_override'] = '';
$route['samsung_galaxy_y'] = "catalog/product/4354";

However it didn't worked for me.

After a long time I find out the reason why it is not working.

There is a small mistake in the internal routing function. It is calling the method (here it is 'product') by passing the 4354 as it is argument.

so if we use a argument in the function like

function product(id=''){
    echo $id;
}

it will print 4354.

But in codeigniter we are fetching it using $this->uri->segment(3)

This will not get the id which is passed to the function.

So I checked the segment() function in URI.php class in system/core directory.

I have found a function which is identical to the above. which is rsegment()

it is for calling the routed.

So finally I made a small change in the segment() function and now it is working great.

Here is the change:

File system/core/URI.php

change the segment() function to following:

function segment($n, $no_result = FALSE)
    {
        $seg = ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n];
        if(!$seg)
            $seg = ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n];
        return $seg;
    }

Hope somebody will find this useful. :)

No comments:

Post a Comment