要限制对页面的访问,可以像下面一样进行检查,
//This code is written on every page accessed by admin. Like, products.php, categories.php
if( !isset($_SESSION['admin_id'])) {
header('Location: admin/login.php');
exit();
}
如果我想限制对控制器的每个方法的访问,那么Codeigniter中上述代码的等价物是什么?
我可以在下面的构造函数中检查会话吗?
//products.php
class Products extends CI_Controller {
public function __construct();
if( !isset($_SESSION['admin_id'])) {
redirect('admin/login.php');
}
}
//categories.php
class Categories extends CI_Controller {
public function __construct();
if( !isset($_SESSION['admin_id'])) {
redirect('admin/login.php');
}
}
答案 0 :(得分:2)
我通常使用的简单方法。
在 application/core
中创建一个控制器 Admin_Controller.php
,并从基本控制器扩展它, 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');
}
}
}
然后,将您的其他管理员相关控制器从 Admin_Controller.php
扩展为,
// application/controllers/products.php
class Products extends Admin_Controller {
public function __construct();
}
// application/controllers/categories.php
class Categories extends Admin_Controller {
public function __construct();
}
现在,您无需检查每个 __contructor()
方法是否为admin。此外,还会跳过一些不需要验证检查的方法,例如登录,注销。
希望这会有所帮助:)
答案 1 :(得分:1)
在某些情况下,越简单越好
class Admin_Controller extends CI_Controller {
public function __construct(){
parent::__construct();
if(!$this->verify_admin_level()){
redirect("home/block");
}
}
private function verify_admin_level(){
return $this->session->userdata("isAdmin");
}
}
主页/阻止只显示消息:您必须以管理员身份登录才能访问所需的功能