Forum Moderators: coopster

Message Too Old, No Replies

Session

Can't get session into a variable

         

Infant89

1:46 am on Jun 9, 2009 (gmt 0)

10+ Year Member



Okay, I'm trying to write a language selection script. For some reason I can't get the value of session 'lang' into the variable $session (see second code line) so $session is always null and the code inside the first if-statement is never run. Everything else works and the session 'lang' is set to $language in the end of the script. When I refresh, the session 'lang' should then be in memory and by placed into $session but for some reason session 'lang' becomes null again.

<?php
session_start();

$session = $_SESSION['lang'];
$cookie = $_COOKIE['lang'];
$server = $_SERVER['HTTP_ACCEPT_LANGUAGE'];

if ($session != null)
{
$language = $session;
}
elseif ($cookie != null)
{
$language = $cookie;
}
elseif ($server != null)
{
$languageArray = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
$lang == "none";

foreach ($languageArray as $value)
{
while ($language != "none")
{
$langArray = substr($value, 0, 2);

switch ($langArray)
{
case "de":
$language = "en"; // should be "de"
break;
case "en":
$language = "en";
break;
case "es":
$language = "en"; // should be "es"
break;
case "fr":
$language = "en"; // should be "fr"
break;
case "is":
$language = "en"; // should be "is"
break;
}
}

if ($language == "none")
$language = "en";
}
}
else
{
$language = "en";
}

$_SESSION['lang'] = $language;
$_COOKIE['lang'] = $language;
?>

enigma1

12:53 pm on Jun 9, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi Infant89 welcome to these forums.

I do not see a problem with your code. The session works. One thing to do is to replace the while with an "if" as your script may hang.

if ($language != "none")

Infant89

6:48 pm on Jun 9, 2009 (gmt 0)

10+ Year Member



What I've done is add echo's to display the values of the variables:

<p>Session: <?php echo $session; ?></p>
<p>_SESSION: <?php echo $_SESSION['lang']; ?></p>
<p>Cookie: <?php echo $cookie; ?></p>
<p>_COOKIE: <?php echo $_COOKIE['lang']; ?></p>

What's interesting is that instead of writing:

Session: is

_SESSION: is

Cookie: is

_COOKIE: is

I get:

Session:

_SESSION: is

Cookie: is

_COOKIE: is

In other words, the sesssion variable is always empty.