Search code examples
phpcodeigniterurl-routingcodeigniter-3

URL routing in PHP Codeigniter


I am having entry in my route.php like - $route['admin/students'] = 'view_student'. Here view_student is controller name. Now when from "localhost/school/admin" page I call <a href="admin/students">Students</a>, than everything works fine; But when I change my route like - $route['/school/admin/students'] = 'view_student', and call it from "localhost/school/admin" page as <a href="/school/admin/students">Students</a>, than 404 page is shown. Whats wrong in here?


Solution

  • Try this code it might help you :

    Here dashboard is the name of controller

    //this will route as localhost/appFolder/admin/index
      $route['admin'] = 'dashboard'; // for your index page
    
    //this will route as localhost/appFolder/admin/method_name
     $route['admin/(:any)'] = 'dashboard/$1';
    
    //this will route as localhost/appFolder/admin/method_name/param1
    $route['admin/(:any)/(:any)'] = 'dashboard/$1/$2';
    

    Link the route Like

    // for your index page
    <a href="<?php echo base_url('admin/index'); ?>"></a>
    
    // for your other pages
    <a href="<?php echo base_url('admin/method_name'); ?>"></a>
    

    To link the other controller defined just like

     <a href="<?php echo base_url('otherControllerName/method_name'); ?>"></a>