Can't set cookie inside construct in codeignit

2019-09-08 06:01发布

问题:

I trying to set a cookie if null but I can't get it to work:

public function __construct()
{
    parent::__construct();
    if ($this->input->cookie('ff', TRUE) == FALSE)
    {
        $this->input->set_cookie('ff', 'on', 86500);
        dump($this->input->cookie('ff', TRUE));
    }
}

What am I doing wrong?

Edit: dump() it's just a custom debug function.

回答1:

A couple of reasons your set_cookie call might fail:

1) You've output something to the browser already when set_cookie is called, in which case you might get an error/notice along the lines of "Headers already sent". To fix that, just ensure that the set_cookie call occurs before sending anything to the browser.

2) If you're doing local development and testing, "localhost" is not considered a valid domain, so no cookies will be saved for it. A workaround would be to add an entry in your hosts file, for example:

localhost.dev    127.0.0.1

And then test with that domain, instead of "localhost".