Topic: Session value into a variable

Okay, I had a problem with variables and sessions and nobody seemed to know what was wrong so I'm including the entire source code so you can run it and see for yourself:

------------
home.php
------------

<?php
    session_start();
    
    $loggedIn = $_SESSION['userID'];
    
    if ($loggedIn == null)
        include("scripts/language.php");
    else
        $language = $_SESSION['lang'];
?>        
<html>
<head>
    <link href="styles/common.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <p><?php echo 'Session var: ' . $_SESSION['lang']; ?></p>
    <p><?php echo 'Cookie var: ' . $_COOKIE['lang']; ?></p>
    <p><?php echo 'Session: ' . $session; ?></p>
    <p><?php echo 'Cookie: ' . $cookie; ?></p>
</body>
</html>

------------
language.php
------------

<?php
    $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)
        {
            if ($lang != "none")
            {
                $langArray = substr($value, 0, 2);
                
                switch ($langArray)
                {    
                    case "de":
                        $lang = "en"; // should be "de"
                        break;
                    case "en":
                        $lang = "en";
                        break;
                    case "es":
                        $lang = "en"; // should be "es"
                        break;
                    case "fr":
                        $lang = "en"; // should be "fr"
                        break;
                    case "is":
                        $lang = "en"; // should be "is"
                        break;
                }
            }
            
            if ($lang == "none")
                $language = "en";
        }
    }
    else
    {
        $language = "en";
    }
    
    $_SESSION['lang'] = $language;
    $_COOKIE['lang'] = $language;
?>

------------
expected results (with my language settings)
------------

Session: is

_SESSION: is

Cookie: is

_COOKIE: is

------------
actual results (with my language settings)
------------

Session:

_SESSION: is

Cookie: is

_COOKIE: is

------------
conclusion
------------

The 'lang' session never seems to be set because the session variable is always null. I asked a mate and had him read my code and he told me he'd had the same problem when he once tried to make a language selection script for his website and he was never able to resolve it. I hope I'm not doomed.

Last edited by Infant89 (June 10, 2009 12:00 pm)

Vote up Vote down