Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP language detection

Tags:

php

I'm trying to build multilangual site.

I use this piece of code to detect users language. If you havent chosen a language, it will include your language file based on HTTP_ACCEPT_LANGUAGE.

I don't know where it gets it from though:

session_start();

if (!isset($_SESSION['lang'])) {
   $_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}

elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'en') $_SESSION['lang'] = "en";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'sv') $_SESSION['lang'] = "sv";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'pl') $_SESSION['lang'] = "pl";
elseif (isset($_GET['setLang']) && $_GET['setLang'] == 'fr') $_SESSION['lang'] = "fr";

include('languages/'.$_SESSION['lang'].'.php');

It works for me and includes the polish lang file. But is this code accurate? Or is there another way?


2 Answers

The browser generally sends a HTTP header, name Accept-Language, that indicates which languages the user is willing to get.

For instance, this header can be :

Accept-Language: en-us,en;q=0.5

There is notion of priority in it, btw ;-)

In PHP, you can get this in the $_SERVER super global :

var_dump($_SERVER['HTTP_ACCEPT_LANGUAGE']);

will get me :

string 'en-us,en;q=0.5' (length=14)

Now, you have to parse that ;-)


If I edit my preferences in the browser's option to say "I want french, and if you can't serve me french, get me english from the US ; and if you can't get me that either, just get me english), the header will be :
Accept-Language: fr-fr,en-us;q=0.7,en;q=0.3

And, from PHP :

string 'fr-fr,en-us;q=0.7,en;q=0.3' (length=26)

For more informations, you can take a look at [section 14.4 of the HTTP RFC][1].

And you probably can find lots of code example in PHP to parse that header ; for instance : Parse Accept-Language to detect a user's language

Have fun !

like image 76
Pascal MARTIN Avatar answered Sep 13 '25 02:09

Pascal MARTIN


Here's the script I used for a bi-lingual site. It is to be used as index.php of mysite.com. Based on the user's browser's language preference, it would redirect to desired language version of the site or the default language site if the site in user's preferred langauge was not available.

<?php
// List of available localized versions as 'lang code' => 'url' map
$sites = array(
    "en" => "http://en.mysite.com/",
    "bn" => "http://bn.mysite.com/",
);

// Get 2 char lang code
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

// Set default language if a `$lang` version of site is not available
if (!in_array($lang, array_keys($sites)))
    $lang = 'en';

// Finally redirect to desired location
header('Location: ' . $sites[$lang]);
?>
like image 28
Imran Avatar answered Sep 13 '25 00:09

Imran