對於笨3我修改韋斯利默奇的回答這個
//創建文件的應用程序/核心/ MY_Controller。PHP
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
function __construct()
{
parent::__construct();
$CI = & get_instance();
$CI->load->library('session');
$CI->load->helper('url');
if (!$this->session->userdata('logged_in'))
{
redirect('login');
}
}
}
然後在任何控制器來檢查我用
類新聞延伸MY_Controller {// 代碼在這裏 }
如果您授權爲網站用戶和管理員使用模塊和不同的會話在用戶,您可以使用此代碼來完美地重定向到不同的登錄pages-
function __construct() {
parent::__construct();
$CI = & get_instance();
$CI->load->library('session');
$CI->load->helper('url');
// echo "<pre>";print_r($this->router);echo "</pre>";
/**
* if webmaster then check admin session else check user session
* But there may be some classes's method that doesn't requires login hence it is also need to check if
* current request is for those methods before checking session
*/
//to use $this->config->item('webmaster_name') this you have to define
// $config['webmaster_name'] = "webmaster"; in config.php file
if ($this->router->module == $this->config->item('webmaster_name')) {
if (!$this->session->userdata('admin')['id']) {
redirect($this->config->item('webmaster_name').'/login');
}
} else {
if (!$this->session->userdata('user')['id']) {
redirect('login');
}
}
}
如果你也希望用戶能夠訪問來自任何特定的控制器的一些方法,而不登錄您可以使用此代碼 -
function __construct() {
parent::__construct();
$CI = & get_instance();
$CI->load->library('session');
$CI->load->helper('url');
//echo "<pre>"; print_r($this->router);echo "</pre>"; //_pr($this->config->item('excluded_auth'));
/**
* if webmaster then check admin session else check user session
* But there may be some classes's method that doesn't requires login hence it is also need to check if
* current request is for those methods before checking session
*/
if ($this->router->module == $this->config->item('webmaster_name')) {
if (!$this->session->userdata('admin')['id']) {
redirect($this->config->item('webmaster_name') . '/login');
}
} else {
if (array_key_exists($this->router->class, $this->config->item('exclude_auth')) && in_array($this->router->method, $this->config->item('exclude_auth')[$this->router->class])) {
//echo "escape this method. don not validate for a session";
} else {
if (!$this->session->userdata('user')['id']) {
redirect('login');
}
}
}
}
注:您可以定義自定義配置文件定義像原樣
//save file in application/config/without_auth_methods.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$config['exclude_auth']['news'] = array('index', 'view');
$config['exclude_auth']['users'] = array('index');
您的排除方法,我建議ÿ ou爲用戶進程使用庫。 Aauth對此很有幫助。 https://github.com/emreakay/CodeIgniter-Aauth – 2013-10-05 14:20:40