【发布时间】:2011-10-15 18:25:42
【问题描述】:
我想在 Codeigniter 中使用 cookie 保持登录状态,但我无法在 Codeigniter 中设置 cookie。这是我在 Controller 中的代码。当我单击登录表单中的提交按钮时,它会调用 chk_login() 函数来检查数据库中的用户名和密码。之后,它会转到这一行 echo "You are not log in" 而已。如何在 Codeigniter 中使用 cookie。
<?php
class Login extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper('cookie');
}
function index()
{
redirect('login/form_login');
}
function form_login()
{
$data['title'] = 'Login';
$this->load->view('form_login_view', $data);
}
function goto_test()
{
if($this->input->cookie('login')){
echo "You are logged in";
}
else{
echo "You are not log in"; // It show string in this line every time. that mean cookie not set yet. how to use cookie in Codeigniter.
}
}
function chk_login()
{
$this->load->model('login_model', 'login');
$this->login->username = $this->input->post('username');
$this->login->password = $this->input->post('password');
$user_login = $this->login->get_by_user_pass();
if($user_login==null){
$data['errors'] = 'Not found Username.<br />';
$this->load->view('form_login_view', $data);
}else{
// I set directed data in cookie but I can't get this cookie in goto_test().
$this->input->set_cookie(array(
'login'=>TRUE,
'username'=>"aaa",
'password'=>"123",
'status'=>"user"));
redirect('login/goto_test'); // Go to function goto_test in this class
}
}
}
?>
我尝试使用此代码进行测试,它显示 bool(false)。
$cookie = array(
'name' => 'test_cookie',
'value' => 'test',
'domain' => '/',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
var_dump($this->input->cookie('name'));
【问题讨论】:
-
您在哪里实际设置了您要验证的 cookie?
-
我想我会尝试使用 JavaScript 验证表单。我应该如何处理 cookie。
-
字符串“$this->input->set_cookie()”在哪里?
-
$this->input->set_cookie() 在函数 chk_login() 的 else{ } 中。
$this->input->set_cookie(array( 'login'=>TRUE, 'username'=>"aaa", 'password'=>"123", 'status'=>"user")); -
试试这个:redirect('login/goto_test', 'refresh');
标签: php codeigniter cookies