Sha*_*bib 8 session-variables codeigniter-2
我是codeigniter的新手.我使用登录表单作为管理员登录.当管理员使用正确的用户名和密码登录时,他/她被引导到带有会话变量的主页.然后,如果他点击退出按钮,会话应该被销毁并将用户重定向到登录页面即登录表单页面.
第一个控制器是管理员:
<?php
class Admin extends CI_Controller
{
function index()
{
$data['main_content'] = 'admin/log_in';
$this -> load -> view('includes/admin/admin_template', $data);
}
function log_in()
{
$this->load->model('admin_model');
$query = $this -> admin_model -> validate();
if ($query)// if the user's credentials validated...
{
$data = array('user_name' => $this -> input -> post('user_name'), 'is_logged_in' => true);
$this -> session -> set_userdata($data);
redirect('admin/home/admin_home');
} else// incorrect username or password
{
$this -> index();
}
}
function log_out()
{
$this->session->sess_destroy();
redirect('/admin/admin','refresh');
}
}
Run Code Online (Sandbox Code Playgroud)
第二个控制器是家庭控制器:
<?php
class Home extends CI_Controller
{
function __construct()
{
parent:: __construct();
$this->is_logged_in();
}
function is_logged_in()
{
$is_logged_in = $this -> session -> userdata('is_logged_in');
if (!isset($is_logged_in) || $is_logged_in != true)
{
$this -> load -> view('admin/forbidden');
}
}
function admin_home()
{
$data['main_content'] = 'home_view';
$this->load->view('admin/home_view');
}
}
Run Code Online (Sandbox Code Playgroud)
该模型是admin_model:
<?php
class Admin_model extends CI_Model
{
function __construct()
{
parent:: __construct();
}
function validate()
{
$this->db->where('user_name',$this->input->post('user_name'));
$this->db->where('password', $this->input->post('password'));
$query = $this->db->get('user');
if($query->num_rows==1)
{
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,它假定用户注销并销毁会话,但是如果我单击浏览器的后退按钮,我可以获得本应该没有的页面,并且会话不会被销毁.请告诉我这里我做错了什么.我正在使用codeigniter 2.1.0.
Sha*_*bib 11
经历了所有麻烦并在各个地方搜索后,我终于找到了解决这个问题的正确方法.问题到了,因为浏览器显示了缓存的页面.这不是创建问题的会话,而且工作正常.这里是解决方案:在家庭控制器中添加一个清除缓存并在构造函数中调用它的函数诀窍:)这里是带有解决方案的家庭控制器:
<?php
class Home extends CI_Controller
{
function __construct()
{
parent:: __construct();
$this->is_logged_in();
$this->clear_cache();
}
function is_logged_in()
{
if (!$this->session->userdata('is_logged_in'))
{
redirect('/admin/admin');
}
}
function clear_cache()
{
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate, no-transform, max-age=0, post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
}
function admin_home()
{
$data['main_content'] = 'home_view';
$this->load->view('admin/home_view');
}
}
Run Code Online (Sandbox Code Playgroud)
现在感谢这个链接" 代码点火器中的注销功能 ",这里是我找到解决方案的地方,它完美地工作:)
如果您注销,那么尽管会话已销毁,会话用户数据仍会在当前 CI 页面构建期间保留。
作为预防措施,您应该这样做:
function log_out()
{
$this->session->sess_destroy();
// null the session (just in case):
$this->session->set_userdata(array('user_name' => '', 'is_logged_in' => ''));
redirect('/admin/admin');
}
Run Code Online (Sandbox Code Playgroud)
参见:http : //codeigniter.com/forums/viewthread/110993/P130/#662369
| 归档时间: |
|
| 查看次数: |
21328 次 |
| 最近记录: |