Welcome Guest, Not a member yet? Register   Sign In
Can't set cookie
#1

[eluser]veledrom[/eluser]
Hi,

Code below never sets a cookie! Do I miss anything?

Thanks

VIEW
Code:
<a href="&lt;?php echo site_url('language/set_language/en'); ?&gt;">English</a>

CONTROLLER
Code:
class Language extends CI_Controller
{
var $cookie_name = 'language';
var $language_code = null;

public function __construct()
{
  parent::__construct();
  
  $this->load->helper('url');
  
  if ($this->uri->segment(3) === false)
  {
   redirect();
  }
  
  $this->language_code = trim($this->uri->segment(3));

  $this->load->helper('cookie');
}

public function set_language()
{
  $cookie = array(
      'name'  => $this->cookie_name,
      'value'  => $this->language_code,
      'expire' => '86500',
      'domain' => 'language.com',
      'secure' => true
      );
      
  set_cookie($cookie);
  
  if (! get_cookie($this->cookie_name))
  {
   echo 'Cookie not set';
  }
  else
  {
   echo get_cookie($this->cookie_name);
  }
}
}
#2

[eluser]veledrom[/eluser]
Anyone there? Or anyone understand cookies???
#3

[eluser]CroNiX[/eluser]
You can't read a cookie until the next request because it hasn't been written yet. It gets set when the whole page is sent as it gets transmitted along with the headers and not immediately when you call set_cookie(). The data is meant to be used in subsequent requests, not the current one.

http://php.net/manual/en/function.setcookie.php
#4

[eluser]CroNiX[/eluser]
Also, I assume you're using SSL on the server since you are using a "secure" cookie.
#5

[eluser]veledrom[/eluser]
Thanks for replying.

I've changed example and added redirect(); and added another function to read the cookie but this example doesn't work either. How do I modify this example make it work?

Sorry for being pain.

VIEW
Code:
<p>
<a href="&lt;?php echo site_url('welcome/set_language/english'); ?&gt;">English</a>
<br />
<a href="&lt;?php echo site_url('welcome/set_language/spanish'); ?&gt;">Spanish</a>
</p>
<br />
<p><a href="&lt;?php echo site_url('welcome/get_language'); ?&gt;">Get Language</a></p>

CONTROLLER
Code:
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'
       );
  
   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);
  }
}
}




Theme © iAndrew 2016 - Forum software by © MyBB