How to run code before every controller in CodeIgniter

I have been working on my side project PostRecycler recently which I have re-written to use the CodeIgniter framework. I came across an interesting challenge where I needed to run some code before every other controller.

What I wanted was to prevent a user from moving away from the dashboard page if their account had expired but what I didn’t want to do was to have to remember to put that into every controller. I guess I could have done it as a helper function but that still would have meant putting a call to it in every controller. MY_Controller to the rescue!

Codeigniter has, of course, thought of this and provides a mechanism to extend the core controller with your own code from which you can then extend your own controllers.

To do this create a new file called MY_Controller.php and save it in the application/core folder. Into it put the following code and add your own functionality too.

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class MY_Controller extends CI_Controller

 function __construct()

    // your code here


/* End of file MY_Controller.php */
/* Location: ./application/core/MY_Controller.php */

When I first did this I was initially confused as to why it wasn’t working. That was because I hadn’t extended my own controller to include the global controller MY_ that I had created. Make sure your controllers look like this.

Basically it is like this (using the above example) CI_Controller -> MY_Controller -> Admin.

And that’s it. With this simple change you have control over what happens before your own controllers are called.

Leave a Reply

Your email address will not be published. Required fields are marked *