0

I'm having some trouble handling cookies. Initially I have set the cookie value to 0. When a user navigates to next page, I want to increment the cookie value by one. My controller is like this:

class Welcome extends CI_Controller {

    public function index() {
        $this->load->helper('cookie');
        $this->input->set_cookie("starttime", time(),time()+3600);
        $this->input->set_cookie("pagevisited",0,time()+3600);
        $_SESSION['currenttime'] = time();
        $this->load->view('indexpage');
    }

    public function page1() {
        $this->load->helper('cookie');
        $value = $this->input->cookie("pagevisited");
        $this->input->set_cookie("pagevisited",$value+1,time()+3600);
        $this->load->view('page1');
    }

    public function page2() {
        $this->load->helper('cookie');
        $value = $this->input->cookie("pagevisited");
        $this->input->set_cookie("pagevisited",$value+1,time()+3600);
        $this->load->view('page2');
    }
}

The above code is not working. The cookie value is still 0. I noticed that CI is also storing session variables with the same cookie name.

Cœur
  • 37,241
  • 25
  • 195
  • 267
curious_coder
  • 2,392
  • 4
  • 25
  • 44
  • 1
    At the top of your class, put public function __construct() { $this->load->helper('cookie') }, that way you can use it in all methods and you don't have to load it every time =) – Crowlix Apr 10 '13 at 08:11
  • yup!Shall keep this in mind. Thanks Crowlix – curious_coder Apr 10 '13 at 11:43

1 Answers1

4

I think your cookie syntax isn't correct. The CodeIgniter manual says only the name and value are required, but to add additional parameters you need to set them all or define an array, I believe. Here are two methods of defining the cookie you want.

$cookie = array(
    'name'   => 'The Cookie Name',
    'value'  => 'The Value',
    'expire' => '86500'
);

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

Or

$this->input->set_cookie($name, $value, $expire, $domain, $path, $prefix, $secure);
James
  • 1,394
  • 2
  • 21
  • 31
Crowlix
  • 1,269
  • 9
  • 19