The Controller receives the user input and validates it, and then passes the input to the Model. It performs interaction on the model objects.

It is a simple class file. The name of the class is associated with URI. The first letter of a class name must be capital.

For example, Welcome.php

class Welcome extends CI_Controller {
	
	public function index() {
		// write your code
		echo "Welcome to CodeIgniter";
	}
}

 

The Welcome class extends an in-built class called CI_Controller. This class must be extended whenever you want to make your Controller class.

 

Calling a Controller

The above controller can be called by URI as follows −

http://localhost/blog/index.php/Welcome/

In the above Welcome.php example index() is the method. If you run with only the class name in the URL by default the index() method will be executed. If you want to add another method then we have to create another function like the following example.

class Welcome extends CI_Controller {
	
	public function index() {
		// write your code
		echo "Welcome to CodeIgniter";
	}

	public function about_us() {
		echo "Infovistar.com";
	}

}

To get the output of the second method using the URL is:

Run in URL:

http://localhost/blog/index.php/Welcome/about_us

 

How to set Default Controller in CodeIgniter?

To specify a default controller, open your application/config/routes.php file and set this variable:

$route['default_controller'] = welcome;

Here ‘welcome’ is the name of the controller class. If you now load your main index.php file without specifying any URI segments you’ll see a “Welcome to CodeIgniter” message by default.

How to pass URI Segments or parameters to the method in CodeIgniter

If a URI contains more than two segments they will be passed to your method as parameters.

For example,

http://localhost/blog/Welcome/user_details/Junaid/25

Here,

http://localhost/blog		= base url	URI segment 0
Welcome				= Controller	URI segment 1
user_details			= Method	URI segment 2
Junaid				= Parameter1	URI segment 3
25				= Parameter2	URI segment 4
class Welcome extends CI_Controller {
	
	public function user_details($name, $age) {
		echo "My name is ".$name." and I am ".$age." years old.";
	}

}

 

 

The name of the controller class must start with an uppercase letter.

Do not use the same name of the method as your parent class, as it will override the parent class’s functionality.