Sean H Jenkins
Sean H Jenkins

Reputation: 1780

CodeIgniter Cookie won't set but Session is working?

I'm working with CodeIgniter to set up some user login functions to my site using Twitter and Facebook, this parts working and the session works fine.

When I try to set a cookie it doesn't work

//Setup a guid
$guid = uniqid();

//Setup a random cookie and point it to db user
$cookie = array(
  'name'   => 'TheCookieName',
  'value'  => $guid,
  'expire' => 100,
  'domain' => BASE_URL,
  'secure' => TRUE
);

    set_cookie($cookie);

  var_dump(get_cookie('TheCookieName')); // bool(false)

My autoload file is simple enough

$autoload['helper'] = array('paging_helper','url','cookie');

I'm obviously missing something trivial? Any clue?

Thanks

Upvotes: 1

Views: 5331

Answers (3)

Abhinav Saraswat
Abhinav Saraswat

Reputation: 819

make sure you set secure => TRUE for https only

Upvotes: 2

Repox
Repox

Reputation: 15474

The problem is probably within your domain variable BASE_URL, which isn't a part of CI constants, probably doesn't contain what you expect or what a cookie initialization requires.

Try doing it like this:

//Setup a guid
$guid = uniqid();

//Setup a random cookie and point it to db user
$cookie = array(
  'name'   => 'TheCookieName',
  'value'  => $guid,
  'expire' => 86500, // have a high cookie time till you make sure you actually set the cookie
  'domain' => '.example.org', // the first . to make sure subdomains isn't a problem
  'path' => '/',
  'secure' => TRUE
);

    set_cookie($cookie);

Remember that cookies will never be available until a new request have been made.
Redirect to another page on the domain specified in the cookie setup and check for the cookie again.

Upvotes: 2

Mob
Mob

Reputation: 11106

You cannot set and access a cookie in the same instance. You should either redirect after setting the cookie or refresh. That's the reason why var_dumping get_cookie would always return false. You should also set the rest of the arguments. See setcookie

Upvotes: 1

Related Questions