Welcome Guest, Not a member yet? Register   Sign In
I have problem with set cookie in codeigniter
#1

[eluser]Unknown[/eluser]
Hello everybody!

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

Code:
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.
#2

[eluser]Matias Perrone[/eluser]
mr.hongphuoc,

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:

Code:
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".

Best!
#3

[eluser]Narf[/eluser]
... 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.




Theme © iAndrew 2016 - Forum software by © MyBB