is_logged_in检查每一页

is_logged_in检查每一页

问题描述:

I am using CodeIgniter. I have a controller named abc and i has functions named index,a,bandc.

www.example.com/abc/

I want that user can only access the area he is logged in.

www.example.com/abc/                    //if loggged in else back to homepage

or

 www.example.com/abc/a/                    //if loggged in else back to homepage

Now to check login. I use:

if($this->auth->is_logged_in()) { .. } else { redirect('/'); }

on every function individually.

Is there any other way to do so ??

I think you can do this by overriding the constructor and call your function in it.

<?php
class Blog extends CI_Controller {

       public function __construct()
       {
            parent::__construct();
            // check login
       }
}
?>

For a particular controller you can put your if check in the constructor of the controller so that when any method of the controller is called it will pass through your if check

class Abc extends CI_Controller {

       public function __construct()
       {
            parent::__construct();
            //your if goes here
       }
}

And if you want to check the user is logged in or not in the whole application you can use the constructor method __construct() of CI_Controller so it will be validated when user access any of the controllers within your application

class CI_Controller {

    private static $instance;

    /**
     * Constructor
     */
    public function __construct()
    {
           //your if goes here

    }

 }