views:

124

answers:

3

My website is language independent, I have several language packs that I include based on user selection.

User selection form:

<form action='' method='POST'>
        <select name='language' onchange='this.form.submit();'>
         <optgroup>
            <option>Language</option>
         <option value='eng'>English</option>
         <option value='esp'>Español</option>
            <option value='fra'>Français</option>
            </optgroup>
        </select>
</form>

The Script:

 $language = $_POST['language'];

 if($language == "esp")
  include("languages/esp.php");
 else if($language == "fra")
  include("languages/fra.php");
 else
  include("languages/eng.php");

The problem is, when I click on a new page on the site, the chosen language is once again forgotten and loads the default English. I know I should be using cookies or sessions to keep the chosen language saved so all pages load that language pack. But how?

A: 

You have to use session_start() on every page if you want to use sessions.

Ondrej Slinták
As @Ondrej mentions, you will need the session_start() on each page you want to use session data on. So, consider putting the code @Chacha102 suggests inside another included file so you are not replicating the same code all over the place.
sberry2A
+3  A: 

On the top of the page:

session_start();
if(isset($_SESSION['language']))
{
     $language = $_SESSION['language'];
}
else
{
     $language = "en";
}

include("languages/".$language.".php");

On the form page:

session_start() // assuming you haven't already done this from the above code

$languages = array("en", "esp", "fra");
if(in_array($_POST['language'], $languages))
{
    $_SESSION['language'] = $_POST['language'];
}

Note that session_start() should only be called once during the page. Normally near the beginning.

Chacha102
+1  A: 

I would use cookies though since we're talking about language selection and the user isn't likely to change his/her language choice. With sessions, if the user closes his/her browser, the language choice is reset. It would be similar to @Chacha102's solution except a little bit more code. You can store the language choice in the cookie by using the function

setcookie()

The cookie is then stored on the user's computer. You can also specify when the cookie will expire. Then you can retrieve the cookie's value (language choice) by using $_COOKIE (similar to $_SESSION).

Definitely read this: http://www.w3schools.com/PHP/php_cookies.asp

Axsuul