a Simple way I usually use.
Create a controller in application/core
as Admin_Controller.php
and Extend it from the base controller, CI_Controller
as,
/* application/core/Admin_Controller.php */
class Admin_Controller extends CI_Controller
{
protected $calledClass ;
protected $calledMethod;
protected $isAuthException;
public function __construct()
{
parent::__construct();
$this->load->library("router");
/*
add the controllers and the methods which don't need auth check.
This is to assign any controller and it's methods to skip the auth
check.
Format : "{CONTROLLER}" => "{A METHOD}", "{Another METHOD}",
*/
$authExceptions = array(
"admin" => array("login", "logout")
);
$this->calledClass = $this->router->fetch_class();
$this->calledMethod = $this->router->fetch_method();
$this->isAuthException = array_key_exists($this->calledClass,$authExceptions) && in_array($this->calledMethod, $authExceptions[$this->calledClass]);
if(!$this->isAuthException && !isset($this->session->userdata('admin_id')))
{
redirect('admin/login.php');
}
}
}
Then, Extend your other admin related controllers from Admin_Controller.php
as,
// application/controllers/products.php
class Products extends Admin_Controller {
public function __construct();
}
// application/controllers/categories.php
class Categories extends Admin_Controller {
public function __construct();
}
Now, you don't need to check in every __contructor()
method whether admin or not. Also some methods such as login, logout which don't need auth check will be skipped.
Hope this helps :)