Welcome Guest, Not a member yet? Register   Sign In
Best way to check if user is logged in
#3

[eluser]alexwenzel[/eluser]
[quote author="Beginers" date="1351123795"]
Code:
class Articles extends CI_Controller {
function __construct()
{
  parent::__construct();
  $this->load->library('usession');
}

public function all()
{
  if($this->is_logged_in())
  {
   //get all article from database
  }
  else
  {
   redirect($this->_login_form);
  }
}

public function delete()
{
  if($this->is_logged_in())
  {
   //remove article
  }
  else
  {
   redirect($this->_login_form);
  }
}
}
[/quote]

This is bad and very redundant design!
What if you want to change the behaviour if a user isnt logged in. You have to touch every controller again.

Better you wrap your "not-logged-in" in a seperate function:

Code:
class Usession extends CI_Session {

    public function  __construct() {
        parent::__construct();
    }

    public static function check_login() {
        $ci = &get;_instance();
        if ( ! $ci->usession->is_logged_in()) {
            redirect('to_login_page');
        }
    }

    public function is_logged_in()
    {
       $logged = $this->userdata('logged_in');
       return ($logged) ? TRUE : FALSE;
    }
}

Now you can add anywhere where you want this call:

Code:
Usession::check_login();

You can even be more flexible by adding special parameter:

Code:
Usession::check_login('redirect_to_page_whatever_if_not_logged');

Code:
Usession::check_login('require_special_permissions');

If you now decide to change your login bevaviour you simply change the check_login() function.


Messages In This Thread
Best way to check if user is logged in - by El Forum - 10-24-2012, 04:07 PM
Best way to check if user is logged in - by El Forum - 10-24-2012, 05:09 PM
Best way to check if user is logged in - by El Forum - 10-25-2012, 02:34 AM
Best way to check if user is logged in - by El Forum - 10-25-2012, 03:18 AM
Best way to check if user is logged in - by El Forum - 10-25-2012, 03:32 AM
Best way to check if user is logged in - by El Forum - 10-25-2012, 04:01 AM
Best way to check if user is logged in - by El Forum - 10-25-2012, 01:34 PM



Theme © iAndrew 2016 - Forum software by © MyBB