Alexander
Alexander

Reputation: 309

Multilanguage website with PHP

I am currently working on a website which will be international, so it needs to come with different languages.

I have a folder named "lang" with files such as en.php, no.php, and so on.. The files consist of an array with different words.

My question is how i should use this. Should i save the language in the persons computer with cookies? Or should I save the ip adress and assign a language to it and save it in the database, or should i pass a &land=en parameter in the url all over the website?

Any ideas and thoughts about how one should handle multilanguage websites?

Best of regarsds, Alexander

Upvotes: 1

Views: 920

Answers (3)

Andris
Andris

Reputation: 27865

If you have the option to use CNAME aliases on your main domain, then one widely used method is to use language specific domain names, eg. in addition to www.site.com there's no.site.com for norwegian, en.site.com for english and so on, which all point to the same website. The language to use is then detected from the current domain name.

This way detecting the language would look something like:

$language = substr($_SERVER['HTTP_HOST'],0,2);

Upvotes: 1

Roman Pietrzak
Roman Pietrzak

Reputation: 615

I used some simple approach... I do maintain the site of calculla. It is like two langs: Polish (PL) and English (EN).

If someone enters the domain calculla.pl then I do assume the default is Polish language. If someone enters the domain calculla.com I assume it is English. But later, each "link" inside the website, can be like calculla.pl/en/something - which turns to english ignoring the default-by-the-domain.

The user can always re-select language by clicking - and then all links "switch" to the language selected.

That's just the one of the possible approaches, but I thought it may fit your needs - there is simply no cookie, no other dependencies, just URL decides.

Upvotes: 0

Michael Berkowski
Michael Berkowski

Reputation: 270599

I think it is probably best to save the user's language in a cookie, so you do not need to pass it around via a querystring parameter. You may also set it in $_SESSION However, you should accept a lang= parameter in each page, which would allow any user to change language easily and instantly. The new language should then overwrite the existing cookie.

$valid_langs = array('en','fr','de','no');
if (isset($_GET['lang'])) {
  // verify that it is a valid language choice before attempting to use it
  // you may store an array of possibilities.

  if (in_array($_GET['lang'], $valid_langs)) {
    $language = $_GET['lang'];
    setcookie('lang', $_GET['lang']);
  }
}
else if (isset($_COOKIE['lang'])) {

  // also be sure to check that the language is a valid choice in a cookie too.
  if (in_array($_GET['lang'], $valid_langs)) {
    $language = $_COOKIE['lang'];
  }
}

Upvotes: 5

Related Questions