我不能在Codeigniter中使用cookie

时间:2011-10-15 18:25:43

标签: php codeigniter cookies

我想在Codeigniter中保持cookie的登录状态,但我无法在Codeigniter中设置cookie。这是我在Controller中的代码。当我点击登录表单中的提交按钮时,它会调用chk_login()函数来检查DB中的用户名和密码。之后,它会转到此行 echo“您不是登录”。如何在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'));

1 个答案:

答案 0 :(得分:0)

现在我知道了。我不能像那样设置cookie。我有2种设置cookie的方式。

1

$cookies = array(
        array(
          'name'   => 'login',
          'value'  => true,
          'domain' => '/',
          'secure' => true
    ),
        array(
          'name'   => 'username',
          'value'  => 'aaa',
          'domain' => '/',
          'secure' => true
    ),
        array(
          'name'   => 'password',
          'value'  => '123',
          'domain' => '/',
          'secure' => true
    )
);

foreach($cookie in $cookies){
        $this->input->set_cookie($cookie); 
}

2

setcookie('login', true);
setcookie('username','aaa');
setcookie('password','123');

Cookie无法像这样设置。

$cookie = array(
          'login'   => TRUE,
          'username'  => 'aaa',
          'password' => '123'
          );

$this->input->set_cookie($cookie);