user2897922
user2897922

Reputation: 79

php cookie not working after reload

I am now working on my language script and I use cookies:

setcookie("lang", "nl", time() + (24 * 60 * 60));
if(isset($_GET['lang'])) {
    $_COOKIE['lang'] = $_GET['lang'];
}

If I go to mysite/?lang=en the site will be in English but when I go to mysite/ is back in the main language (dutch). The cookie is set, I can see the information in Google Chrome but its not working.

Print_r(mysite/) (before set language)

Array ( [lang] => nl ) 

Print_r(mysite/?lang=en) (set the new language)

Array ( [lang] => en )

Print_r(mysite/) (after remove ?lang=en)

Array ( [lang] => nl ) 

I know this script is now unsafe but its not working now. I will add the security after its working.

Upvotes: 0

Views: 962

Answers (1)

Legionar
Legionar

Reputation: 7607

Its because you set language in cookie each time to "nl", you visit the site, and only if you has $_GET['lang'] setted, then you set it to another language; but without $_GET['lang'] its again reseted to "nl".

setcookie("lang", "nl", time() + (24 * 60 * 60));

if(isset($_GET['lang'])) {
    $_COOKIE['lang'] = $_GET['lang'];
}

It should be:

if (!isset($_COOKIE['lang'])) {
    setcookie("lang", "nl", time() + (24 * 60 * 60));
}

if (isset($_GET['lang'])) {
    setcookie("lang", $_GET['lang'], time() + (24 * 60 * 60));

    $_COOKIE['lang'] = $_GET['lang'];
}

When you use setcookie, it will not be stored in $_COOKIE, only after next load of site.

Upvotes: 1

Related Questions