views:

82

answers:

3

I have a controller called member within this a construct function

function __construct() { parent::Controller(); $this->is_logged_in(); }

I want to check in my other controller that user is logged in how i can use this function in my other controller called profile and others

This is my First project with CodeIgniter

Thank you

A: 

I don't think that doing it with the class is the best idea. If the user is logged in, you should check for a flag (value or whatever) inside the session, so you don't need to work with the other controller.

The advantage would be that the session can be accessed more easily and it is the more common approach.

DrColossos
If someone downvotes, at least say why...
DrColossos
+2  A: 

Your authentication checks should be in a library:

The is an excerpt from a basic codigniter authentcation script:

class Site_sentry 
{
    function Site_sentry()
    {
        $this->obj =& get_instance();
    }

function is_logged_in()
{
    if ($this->obj->session) 
    {
        if ($this->obj->session->userdata('session_logged_in'))
        {
            return TRUE;
        }
        else
        {
            return FALSE;
        }
    }
    else
    {
        return FALSE;
    }
} 

   function login_routine()
   {
     //do login here (enter into session)
   }
}

This library is stored in application/libraries under a filename named after its class with the .php suffix.

Then you can either add this to your autoload config file application/conig/config.php:

$autoload['libraries'] = array('database', 'site_sentry', 'session');

or load it manually in each controller:

$this->load->library('Site_sentry);

Then you can check your session from within controllers, like so:

 class Class extends Controller{

    function Class()
    {   
       parent::Controller();
       if( $this->site_sentry->is_logged_in() == FALSE){
            redirect('managerlogin/');
        }

    }
   }

Also check this documentation page http://codeigniter.com/user_guide/libraries/sessions.html; of particular interest is the storing the session into the database section.

DRL
Thank you very much
saquib
A: 

Example with session:

class SomeClass extends Controller {

function __construct()
{
    parent::Controller();   
    $this->is_logged_in();
}   

function is_logged_in()
{

    $is_logged_in = $this->session->userdata('is_logged_in');
    if(!isset($is_logged_in) || $is_logged_in != TRUE) 
    {
        redirect('login');
    }
}
Vasil Dakov