Creating a controller in CodeIgniter
PHP CodeIgniter

Creating a controller in CodeIgniter

Editorial Team
Editorial Team

Follow us on Discord or Telegram to get access to free tutorials and updates.

What is a controller?

The controller acts as an interface between Model and View components to manage all the business logic and interact with the Views to give the output. In other words, the controller translates actions by the user in view to actions and returns results back to the user.

Creating a controller

To create a new controller,

  • Go to root_directory->application->controllers.
  • Create a new file PublicController.php.
  • Add the following code:
<?php defined('BASEPATH') or exit('Direct code access is not allowed'); 
class User extends CI_Controller { 	
	//Your logic here 
} 
?>

Every controller should be extended from CI_Controller.

  • Add a new controller function
<?php
defined('BASEPATH') or exit('Direct code access is not allowed');
class PublicController extends CI_Controller{
	public function index()
    {
    	$this->load->view('public/index');
    }
}
?>

The index method looks for a page named index under root_directory->application->views->public.

Checking whether the page exists or not

Add the following code if you need to need to make sure that the page exists or not.

<?php
defined('BASEPATH') or exit("You are not allowed to view this page");

class PublicController extends CI_Controller{
	public function index($page="index")
    {
    	if(!file_exists(APPPATH.'views/public/'.$page.'.php'))
        {
        	show_404();
        }
        else
        {
        	$this->load->view('public/'.$page);
        }
    }
}
?>
  • APPPATH is a CodeIgniter constant
  • show_404() is an inbuilt function to show a 404 error page.

❌ This code may show an error if you have not created a page named welcome.php at the specified path.

Next page explains about creating a view page for this controller.

DOWNLOAD SOURCE CODE

Download the complete project and refer the following files:

  • cisite/application/config/routes.php
  • cisite/application/controllers/PublicController.php
  • cisite/application/views/public/index.php