Reputation: 79
Good morning,
I've got such problem. I would like to store in cookies language, which user will choose. The value in local variable is still changed, but value in cookie is always the same. Even if I always delete the cookie and then I create it again the value stored in cookie is wrong and my local is good. Here's my code:
<?php
if (isset($_GET['lng'])) {
$lng = $_GET['lng'];
if (($lng != "en") && ($lng != "de")) {
$lng = "en";
}
} else {
if(!isset($_COOKIE['lang'])) {
$lng = "en";
} else {
$lng = $_COOKIE['lang'];
}
}
if(isset($_COOKIE['lang'])) {
setcookie("lang", $_COOKIE['lang'], time()-10); //here I try to remove cookie and then create another
}
setcookie("lang", $lng, time()+5);
print_r($_COOKIE);
echo $lng;
?>
print_r will allways return me the main language (en), even if in variable $lng there is de. I think, there will be just stupid problem, but I can't fix it. This removing line (which I commented) is there because of problem written on official php site:
Be careful of using the same cookie name in subdirectories. Setting a simple cookie
setcookie("region", $_GET['set_region']);
both in the root / and for instance in this case /admin/ will create 2 cookies with different paths. In reading the cookies back only the first one is read regardless of path.
And I thought I've similar problem. But this didn't fix my problem and even when the cookie after 5 second will expire to cookie is then written again the bad "en" value.
Thank for your answer
Upvotes: 1
Views: 2032
Reputation: 1882
Can you try this, it works for me. I edited the code a bit, sorry for obfuscating it with one line if-statements.
I also set the cookie time to 1 day so it won't disappear when testing the code.
And remember, you have to update the page to read the new cookie, it will be one step behind $lng
.
<?php
$allowed = array('en', 'de');
$chosen = $_GET['lng'] ? $_GET['lng'] : ($_COOKIE['lang'] ? $_COOKIE['lang'] : 'en');
$lng = in_array($chosen, $allowed) ? $chosen : 'en';
setcookie("lang", $lng, time()+24*60*60, '/');
var_dump($_COOKIE['lang']);
echo $lng;
?>
Upvotes: 1