Switching languages on a website with PHP

心不动则不痛 提交于 2019-12-04 17:47:34

I would go for session variable.

At the beginning of your pages you'll have:

 if (!isset($_SESSION['language']))
    $_SESSION['language'] = "en";

Then you'll have some links to change the language

<a href="changelanguage.php?lang=es">Español</a>
<a href="changelanguage.php?lang=fr">Français</a>

Changelanguage.php simply is something like

$language = $_GET['lang'];
// DO SOME CHECK HERE TO ENSURE A CORRECT LANGUAGE HAS BEEN PASSED
// OTHERWISE REVERT TO DEFAULT
$_SESSION['language'] = $language;
header("Location:index.php"); // Or wherever you want to redirect

Have you thought about using $_SERVER["HTTP_ACCEPT_LANGUAGE"]? Something like this:

if ($_SERVER["HTTP_ACCEPT_LANGUAGE"]) { 
    $langs = explode(",", $_SERVER["HTTP_ACCEPT_LANGUAGE"]); 
    for ($i = 0; $i < count($langs); $i++) { 
        if ($langs[$i] == "en") { 
            $lang = "en";
            break;
        } 
        elseif($langs[$i] == "es") {
            $lang = "es";
            break;
        }
    } 
}

Of course, a switch statement might fit a bit better here, and there's more ways to say English than only en, but this should work without the user having to do a thing. If they manually change, store it in a cookie as per Ben's answer.

The most common way would be to use it as part of the url and extract it when a page loads:

http://www.your-site.com/en/somepage

Are you using a framework?

The most common way to pass a language identifier is subdomain.

http://en.wikipedia.com/

both subdomains should point to the same directory and actual language can be easily extracted from the HTTP_HOST

and for storing language files the solution is gettext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!