Search code examples
phpcodeignitercodeigniter-routing

URL with trailing slashes leads to different pages - MVC CI


I have a routed like the following in my Code Igniter route file.

$route['profile'] = "profile";

The class profile contains the following

$this->load->view('pages/profile.php');

Now I have a link on my profile.php page which looks like the following

<a href = 'logout'>Logout</a>

Now consider a user using it. If he visits the following url

localhost/project/profile

Then now the link on the profile.php page would lead to the following

localhost/project/logout

But if the user uses this url

localhost/project/profile/

That is if there is a trailing slash then the link on the page would lead to

localhost/project/profile/logout

And now my question is what should I do to lead the link in both the cases to

localhost/project/logout

Hope I am clear. Please help me out


Solution

  • I think that you're searching for this, load the url helper on your controller with this code line

    $this->load->helper('url');
    

    On your view whenever you want to echo URL's use this code

    //this will echo something like this http://(yourdomain).index.php/logout
    <a href = '<?=site_url("logout")?>'>Logout</a>
    

    If you want let's say, an url to another controller you'll use something like this

    //this will echo something like this http://(yourdomain).index.php/(anothercontroller)/logout
    <a href = '<?=site_url("anothercontroller/logout")?>'>Logout</a>
    

    More information about the url helper from codeigniter can be found here: http://ellislab.com/codeigniter/user-guide/helpers/url_helper.html