Extending the Controller Class in CodeIgniter
CodeIgniter is a great little PHP framework that allows you to rapidly build MVC web applications. Without getting too far into Model View Controller ideology, this post will explain how to extend CodeIgniter’s Controller class to achieve site-wide authentication checks.

Not long after starting your fancy new webapp, you will start to realize that putting
if (!isset($_SESSION['isloggedin'])) { redirect('/login'); }
in every single controller function is very tedious.
You can create an extension of the Controller class and put the common code in there. Here’s how.
Create a file in /system/application/libraries called MY_Controller.php. The name of this file is important. If the prefix “MY_” doesn’t do it for you, go into /system/application/config/config.php and change
$config['subclass_prefix'] = 'MY_';
to whatever you want. Don’t change the “Controller” part though! You can also extend Models and Helpers.
Start with the following code in MY_Controller.php:
class Authenticated_Controller extends Controller { function Authenticated_Controller() { parent::Controller(); session_start(); if (!isset($_SESSION['isloggedin'])) { redirect('/login'); } } }
Go ahead and add any common controller functions to this class. Feel free to change “Authenticated_Controller” to whatever you want. You can also have multiple Controller extensions in this file.
Note: If you only have one controller extension, it is standard to name your class MY_Controller (rather than Authenticated_Controller).
Important Note: If you find yourself creating a bunch of controller extensions, take a step back and consider what you are doing. Is your extension being used by only one controller? If so, just put your code in that controller’s constructor.
Now it’s time to start using your new controller extension!
In every controller that requires authentication (don’t do this for your login controller!) rather than the traditional
class Manage extends Controller { ...
use this instead:
class Manage extends Authenticated_Controller { ...
Do you have CodeIgniter controller extensions that could be useful to others? Let us know in the comments.




















Gavin Blair, Developer
1) Clicked on ‘My Website’ where I was using crystal reports