Home » Php » php – CodeIgniter: Page not found when passing parameters to a controller?

php – CodeIgniter: Page not found when passing parameters to a controller?

Posted by: admin July 12, 2020 Leave a comment

Questions:

I’m trying to pass parameters to a control in codeigniter, but I’m getting 404 page not found error, I don’t get it, I did what the guide says: https://www.codeigniter.com/user_guide/general/controllers.html#passing-uri-segments-to-your-methods

When I remove the params in the index function and just access the controller everything works fine, but I can’t pass a value to it…

Here is the code the way I’m trying to send a param: http://mysite/123

<?php
class Main extends Controller {

    function index($username) {

        echo $username;

    }

}
?>

How can I get more info regarding this error from codeigniter?

Thank you.

How to&Answers:

The URL needs to be http://mysite/Main/index/123.

CodeIgniter URLs are http://<url>/<Controller>/<Method>/<params>.

Answer:

Check out the /application/config/routes.php file and set the default controller to main like this:

$route['default_controller'] = 'main';

Answer:

//For CI 2.0.2
//main.php

<?php
class Main extends CI_Controller {

    function index($username) {

        echo $username;

    }

}
?>

// application/config/routes.php
$route[‘default_controller’] = ‘main’;

And then try this in URL::
http://mysite/index.php/main/index/123

hope this works for you

Answer:

As far as I know, the data is passed only when there are more than two uri segments.

Try this,

<?php
class Main extends Controller {

    function index() {
        $username = $this->uri->segment(3);
        echo $username;
    }
}
?>

And then go to http://mysite/index.php/main/index/123

Answer:

Add this function into your control. This will help out get passing arg into index function if method doesn’t.

    function _remap($method)
    {
      $param_offset = 2;

      // Default to index
      if ( ! method_exists($this, $method))
      {
        // We need one more param
        $param_offset = 1;
        $method = 'index';
      }

      // Since all we get is $method, load up everything else in the URI
      $params = array_slice($this->uri->rsegment_array(), $param_offset);

      // Call the determined method with all params
      call_user_func_array(array($this, $method), $params);
    }

Answer:

route file in add this code and any parameters accepted for your home page

$route['default_controller'] = 'main'; 
$route['(:any)'] = "main/$1";