• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I have problem with set cookie in codeigniter

Hello everybody!

I want to set cookie on page load, i put this code in index.php

if (!isset($_COOKIE['LANG'])){
setcookie('LANG', 'en', time()+86500,'/','');


When i enter website on the address bar in browsers as Chrome, IE... Cookie is not set up, i have to refresh website, cookie has done well. I want to set cookie on page load without refreshing my website, what can i do? Thanks for your help.

[eluser]Matias Perrone[/eluser]

This is not a bug, this is a pure PHP problem. You can access the cookies in the next load if you want to save the "LANG" as it was a cookie set it when you call the "setcookie" function, so:

if (!isset($_COOKIE['LANG']))
setcookie('LANG', 'en', time()+86500,'/','');
$_COOKIE['LANG'] = 'en';

Check PHP Manual for the setcookie: http://www.php.net/manual/en/function.setcookie.php, it says "Once the cookies have been set, they can be accessed on the next page load".


... and it's not PHP's problem either. Thats simply how cookies work:

Step 1: HTTP Client <request> HTTP Server
Step 2: HTTP Server <response> HTTP Client

This happens every time you visit a web page. When you call setcookie(), the cookie is sent in Step 2 as a part from the server's response. However, a cookie must be sent by the client (your browser) in Step 1, so that it's data can be available to the server, which happens on your next page load.

Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  

  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.