簡體   English   中英

我無法在Codeigniter中使用Cookie

[英]I can't use cookie in Codeigniter

我想用Codeigniter中的cookie保持登錄狀態,但是我不能在Codeigniter中設置cookie。 這是我在Controller中的代碼。 當我單擊登錄表單中的提交按鈕時,它將調用chk_login()函數以檢查數據庫中的用戶名和密碼。 之后,它僅回顯“您尚未登錄”這一行。 如何在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。 我有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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM