0

Possible Duplicate:
Accessing $_COOKIE immediately after setcookie()

So I am using the following code below to add multilingual features to my site:

if(isset($_GET['lang']) && $_GET['lang'] != ""){
setcookie("lang", $lang, time()+360*360*3600);
}elseif(!isset($_COOKIE["lang"]) || $_COOKIE["lang"] == ""){
setcookie("lang", "en", time()+360*360*3600);
}
include 'lang/'.$_COOKIE["lang"].'.php';

Now when this code gets executed the first time it fails to find the `$_COOKIE["lang"] and therefore fails to open the file, however after when I refresh the page it loads just fine. I was wondering what I am doing wrong?

Community
  • 1
  • 1
Ahoura Ghotbi
  • 2,866
  • 12
  • 36
  • 65
  • 2
    Consider performing some validation on `$_COOKIE["lang"]` before dropping it into an `include` statement to avoid a [path traversal attack](https://www.owasp.org/index.php/Path_Traversal). –  Jun 02 '12 at 21:41

1 Answers1

2

The cookie is only set when you do a request.

That's how it works (it is send with every request). And since you are still in the same request it simply isn't there yet.

But you can set it your own:

if (isset($_GET['lang']) && $_GET['lang'] != "") {
    $_COOKIE['lang'] = $lang;
    setcookie("lang", $lang, time()+360*360*3600);
} elseif ...

That's maybe the work-around you're looking for.

hakre
  • 193,403
  • 52
  • 435
  • 836
PeeHaa
  • 71,436
  • 58
  • 190
  • 262