Calling a Controller function in another Controller in CodeIgniter

I have a controller “user” in my codeigniter application. This controller has a function called logged_user_only():

public function logged_user_only()
        $is_logged = $this -> is_logged();
        if( $is_logged === FALSE)

As this function calls another function called is_logged(), which just checks if the session is set, if yes it returns true, else returns false.

Now if i place this function in the begining of any function within same controller, it will check if the user is not logged, it will redirect to login_form otherwise continue. This works fine.
For example,

public function show_home()
        $this -> logged_user_only();

Now I would like to call this logged_user_only() function in a function of another controller to check if the user is logged in or not?

PS. If this can not be done, or is not recommended, where should i place this function to access in multiple controllers? Thanks.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Why not extend the controllers so the login method is within a MY controller (within the core folder of your application) and all your other controllers extend this. For example you could have:

class MY_Controller extends CI_Controller {
    public function is_logged()
        //Your code here

and your main controllers could then extend this as follows:

class Home_Controller extends MY_Controller {
    public function show_home()
         if (!$this->is_logged()) {
           return false;

For further information visit: Creating Core System Classes

New link is here:

Solution 2

Calling a controller from another is not possible with CI and not recommended.

Either move your logged_user_only into a helper or even better a core controller that you extend all of your controllers from (MY_Controller) see

Solution 3

just load user controller as library from your controller

function __construct(){

Now, call this function of user controller any where in your controller,


Solution 4

Function login in Controller Login

$data =array('username' => $this->input->post('username'), 'password' => $this->input >post('password')) $query = $this->db->get_where('usertable',$data)
    if ($query->num_rows() == 1) {
        $data = array(
            'username' => $this->input->post('username'),
            'logged_in' => TRUE,
            'role' => "user");

Function Construct in Controller user

if ($this->session->userdata('logged_in') == TRUE && $this->session->userdata('role') == "user") {} else {redirect('home');}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply