Home » Php » php – default controller inside subfolder codeigniter 3 not working

php – default controller inside subfolder codeigniter 3 not working

Posted by: admin July 12, 2020 Leave a comment

Questions:

In codeigniter 3 application i have directory structure like this:

-Myproject
  -application
    -controllers
     -home
       Welcome.php   //This is my controller inside home directory

How to set Welcome controller as default controller?
I use below code

$route['default_controller'] = 'home/Welcome';

This routing works for previous versions of codeigniter.

How to&Answers:

By default, you are not allowed to do that. To get around this, you need to hack your system Router.php:

codeigniter/system/core/Router.php

Edit a few lines of code so that it becomes like this:

codeigniter/system/router.php

line 1. if (!sscanf($this->default_controller, '%[^/]/%[^/]/%s', $directory, $class, $method) !== 2)

line 2. if ( ! file_exists(APPPATH.'controllers'. DIRECTORY_SEPARATOR . $directory. DIRECTORY_SEPARATOR .ucfirst($class).'.php'))

line 3. $this->set_directory($directory);

Once you’ve done, you can call the default controller under directory.

$route[‘default_controller’] = ‘home/Welcome’;

Answer:

You need not to change anything from files inside CODEIGNITER system folder. Codeigniter allows developer to extend their feature. You can create a file named as MY_Router.php.

<?php
class MY_Router extends CI_Router {
    protected function _set_default_controller() {

        if (empty($this->default_controller)) {

            show_error('Unable to determine what should be displayed. A default route has not been specified in the routing file.');
        }
        if (sscanf($this->default_controller, '%[^/]/%s', $class, $method) !== 2) {
            $method = 'index';
        }
        if( is_dir(APPPATH.'controllers/'.$class) ) {
            $this->set_directory($class);
            $class = $method;
            if (sscanf($method, '%[^/]/%s', $class, $method) !== 2) {
                $method = 'index';
            }
        }

        if ( ! file_exists(APPPATH.'controllers/'.$this->directory.ucfirst($class).'.php')) {
            return;
        }
        $this->set_class($class);
        $this->set_method($method);
        $this->uri->rsegments = array(
            1 => $class,
            2 => $method
        );
        log_message('debug', 'No URI present. Default controller set.');
    }
}

Note: Do not change the file name.

Answer:

Try This in routes.php

$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;