Welcome Guest, Not a member yet? Register   Sign In
Best place to check if logged-in
#1

[eluser]Craig Ward[/eluser]
Currently I use the following for checking is a user is logged in:

Code:
function only_a_loggedin_user_can_do_this()
{
    if($user_is_logged_in)
    {
       do something that only users can do
    }
    else
    {
        redirect('/login_page/');
    }
}
but if my controller has many functions is a bit of a pain in the arse to write or make changes.

Whats the best way to achieve what I want but in a more simplistic way that is easier to update. I was thinking of the below,

Code:
function check_if_logged_in()
{
    if($user_is_logged_in)
    {
       function only_a_logged-in_user_can_do_this()
       {
       }

       function or_this()
       {
       }

    }
    else
    {
        redirect('/login_page/');
    }
}
but would that mean adding adding something to the URI string, eg

www.example.com/index.php/check_if_logged_in/only_a_logged-in_user_can_do_this/

Whats the best way to implement this?
#2

[eluser]danmontgomery[/eluser]
Code:
class Some_controller extends CI_Controller {

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

    public function method_a() {
        $this->_check_logged_in();

        // Do something else
    }

    private function _check_logged_in() {
        if(!$user_is_logged_in) {
            redirect('login_page');
        }
    }

}

I would probably put something like that in a base controller, however, assuming it would need to be used across multiple controllers.
#3

[eluser]Craig Ward[/eluser]
Thats looks perfect, cheers Smile
#4

[eluser]JuanitoDelCielo[/eluser]
My favorite way it's extend the CI_Controller class adding the method and it will be avaliable to every single controller.
#5

[eluser]JuanitoDelCielo[/eluser]
I found it again Tongue http://philsturgeon.co.uk/news/2010/02/C...ing-it-DRY
#6

[eluser]lalouze78[/eluser]
You also can use a pre-controller hook with a CI_Controller extended class.
This method allow you to check if user is logged in and change directly controller and method called without use a redirect() like function.
#7

[eluser]mdvaldosta[/eluser]
Extend the base controller and put the check in there, that way it doesn't have to be duplicated for every controller. Just like Sturgeon's article suggests.




Theme © iAndrew 2016 - Forum software by © MyBB