For any queries you can reach us at infovistarindia@gmail.com / WhatsApp us: +919158876092

Controller in CodeIgniter

Introduction

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.

Example: Welcome.php

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

Run in URL: http://localhost/blog/index.php/Welcome/

Output will be:

Welcome Controller

In the above Welcome.php example index() is the method. If you run with only the class name in 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

Output will be:

Welcome Controller 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 "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/index.php/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 output will be:

Welcome Controller user_details