As its name suggest that it is a Controller that controls the web application, and it works as an intermediary between the Models and the View. A controller takes requests from the user via HTTP and passes these requests to the model and view to provide a relevant result to the user. Due to this, it is the main part of the CodeIgniter application, which handles the server request. A controller also contains an action or function to perform a particular task. And you can define multiple methods in the controller class. Furthermore, a controller can also load the model and the view file.  

Create a Controller

Here we have described some steps for creating a Controller.

You can use visual studio, notepad++, sublime, or any other editors for creating CodeIgniter web application. Here we are using visual studio for developing a web application.

Firstly, go to the CodeIgniter-3.1.11 folder and click on it. Then you will see, three folder application, system, and user_guide


After that, click on the application folder, where you will see many sub-folders inside the application folder like the given below image.


Now click on the Controller folder, and then, you will see some predefined files, as shown in the given below image.


Now, Right-click on the controller’s folder and create a New File, as shown in the given below image.


Now you can define a controller file name with the php extension. In this, we have created an Users.php file of the controller. You should remember that the first letter of the file in uppercase, as we have taken in the image given below.


After providing the name of the controller file, press the Enter button from your keyboard. And then, your screen will look like the image given below.


Example: Create a Users.php file inside the Application/Controller and then write the given below code in your file.

The above statement shows that a controller can’t be accessed directly. It means if you want to access or run your controller in the web browser, then you have to define the index.php file before the controller’s name. An index.php file is the main file through which the queries pass to the controller. Therefore, you have to always use an index.php file in the localhost’s URL before calling the controller.

Now run your code on the localhost server by writing this localhost/CodeIgniter-3.1.11/index.php/Users/index



In the above output, CodeIgniter-3.1.11 is the primary folder name in which all your sub-folder present, index.php file is the main file through which your queries pass to the controller, Users is the Controller name, and an index is the method name. 

Note: You can also define the multiple actions inside the controller class.

Example: Create multiple methods in the Users’ Controller class.

In the above program, we have created multiple methods like index, second, and last. Now we will execute all the methods one by one.







Pin It on Pinterest

Share This