For some reason I cannot set a cookie with an simple example. Every example I found on web failed too. I wonder if I miss something little. Keeps saying “Cookie not set“
I added REFRESH after setting cookie and another method *get_language()* to read it via link clicking but still no luck.
Thanks in advance
VIEW
<p>
<a href="<?php echo site_url('welcome/set_language/english'); ?>">English</a>
<br />
<a href="<?php echo site_url('welcome/set_language/spanish'); ?>">Spanish</a>
</p>
<br />
<p><a href="<?php echo site_url('welcome/get_language'); ?>">Get Language</a></p>
CONTROLLER
class Welcome extends CI_Controller
{
var $cookie_name = 'language';
public function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('cookie');
}
public function index()
{
$this->load->view('welcome_message');
}
public function set_language()
{
if($this->uri->segment(3) != false)
{
$cookie = array(
'name' => $this->cookie_name,
'value' => $this->uri->segment(3),
'expire' => '86500',
'domain' => '.language.com',
'secure' => true
);
set_cookie($cookie);
redirect(null, 'refresh');
}
}
public function get_language()
{
if (! get_cookie($this->cookie_name))
{
echo 'Cookie not set';
}
else
{
echo get_cookie($this->cookie_name);
}
}
}
You won’t be able to see/use the cookie before reloading the page. That means you need to implement page refresh somewhere after set_cookie($cookie); before you get the state of it.
Another thing, you may wanna change
to
to make sure your cookie is accessable withing the http://www.language.com, http://language.com and other subdomains.