I want to keep login status with cookie in Codeigniter, but I can’t set cookie in Codeigniter. This is my code in Controller. when I click submit button in the login form it call chk_login() function to check username and password in DB. After that, it go to this line echo “You are not log in” only. how to use cookie in Codeigniter.
<?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
}
}
}
?>
I try to test with this code it show bool(false).
$cookie = array(
'name' => 'test_cookie',
'value' => 'test',
'domain' => '/',
'secure' => TRUE
);
$this->input->set_cookie($cookie);
var_dump($this->input->cookie('name'));
Now I know that. I can’t set cookie like that. I have 2 way for set cookie.
1.
2.
The cookie can’t set like this.