开发者

How to use PHP sessions or cookies to achive this?

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 a开发者_JAVA百科ll pages load that language pack. But how?


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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜