You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<?php
/*在CI框架的项目开发过程中,需要对用户登录状态进行验证和跳转,如果每个页面或者每个控制器都写相同的代码,就非常浪费开发效率,并且代码臃肿,相当的麻烦。
下面介绍一种方法,既然可以有全局控制器,那么就在全局控制器中添加登录态的判断,其他继承自该控制器的每个控制器中,自定义是否需要登录状态的判断。具体实现代码如下!
首先打开CI框架根目录->system->core->Controller.php,添加代码(根据注释添加):
*/
public $need_login = false;//添加登录状态属性
/**
* Constructor
*/
public function __construct(){
self::$instance =& $this;
// Assign all the class objects that were instantiated by the
// bootstrap file (CodeIgniter.php) to local class variables
// so that CI can run as one big super object.
foreach (is_loaded() as $var => $class){
$this->$var =& load_class($class);
}
$this->load =& load_class('Loader', 'core');
$this->load->library('session');//开启session
$this->load->initialize();
$this->check_login();//调用判断登录的方法
log_message('debug', "Controller Class Initialized");
}
private function check_login(){//判断登录的方法
if($this->need_login){
$session_data = $this->session->userdata('user');
if(!$session_data){
$url = "/phpthinking";
echo "<script language='javascript' type='text/javascript'>";
echo "window.location.href='$url'";
echo "</script>";
exit;
}
}
}
//在其他子控制器中,只要添加如下代码就可实现功能:
public function __construct(){
$this->need_login = true;//控制是否需要登录
parent::__construct();
}
;?>
The text was updated successfully, but these errors were encountered:
CI框架设置全局登录限制
The text was updated successfully, but these errors were encountered: