我遵循了如何在codeigniter中为php应用程序设置登录系统的教程。当用户拥有会话数据时的逻辑运行良好,但是当用户没有登录时我遇到了问题(f.ex.一段时间后刷新页面)。 " not_logged_in"的视图当我从构造函数调用functin时,会执行两次。 以下代码有效,但这意味着我必须为我之后添加的每个函数添加代码。
class App extends CI_Controller {
function __construct()
{
parent::__construct();
}
private function logged_in()
{
$is_logged_in = $this->session->userdata('is_logged_in');
if (isset($is_logged_in) OR $is_logged_in)
{
return TRUE;
}
else
{
$data['title'] = 'Chyba přihlášení';
$data['main_content'] = 'not_logged_in';
$this->load->view('includes/template', $data);
return FALSE;
}
}
function index()
{
if($this->logged_in())
{
$data['title'] = 'APLIKACE';
$data['main_content'] = 'app_view';
$data['userid'] = $this->session->userdata('userid'); //get userid from session
$this->session->unset_userdata('userid'); //destroy the data
$this->load->view('includes/template' , $data);
}
}
function logout()
{
$this->session->sess_destroy();
redirect('login');
}
}
现在真正的问题是,如何将整个逻辑放入构造函数中而不必在每个函数中检查它?
答案 0 :(得分:0)
创建APPPATH.'core/MY_Controller.php'
文件并将认证逻辑放在构造函数中。然后从每个控制器扩展该类(您需要auth逻辑)。
class MY_Controller extends CI_Controller
{
public function __construct();
{
parent::__construct();
$this->check_login();
}
protected function check_login()
{
$is_logged_in = $this->session->userdata('is_logged_in');
//here should be *AND* instead *OR* logic
if (isset($is_logged_in) && !empty($is_logged_in))
{
return TRUE;
}
else
{
redirect('login/index');
exit();
}
}
}
Login.php控制器:
class Login extends CI_Controller//NOT extending MY_Controller to avoid infinite loop
{
public function __construct();
{
parent::__construct();
}
public function index()
{
//here is login view
//and logic of preserving session
//with redirect to 'app/index' after successful login
}
public function logout()
{
$this->session->sess_destroy();
redirect('login');
}
}
App.php控制器:
class App extends MY_Controller//extending MY_Controller to check login status
{
public function __construct();
{
parent::__construct();
}
public function index()
{
//here is app dashboard view
}
public function statistics()
{
//here is some other method that requires logged in user
}
}
我还建议您检查Ion_auth身份验证系统,看看是否适合您。