Home

Implementing the Detect Browser Language Class

Download the example file.

The Detect Browser Language Class is written in the PHP programing language. To set the default language just enter the required language code for $default_language, for example, $default_language = 'en';.

To get started create a PHP page with the following sections.

Start a session

if (!(isset($_SESSION))) session_start();

Include the Detect Browser Language Class file

include_once ('detect_language_class.php');

Check if a language been set

if (isset($_GET['lang'])){
		$_GET['lang'] = $_GET['lang'];
	}elseif (isset($_SESSION['user_language_choice'])){
		$_GET['lang'] = $_SESSION['user_language_choice'];
	}else{
		$_GET['lang'] = $locale->default_language;
}

Switching the languages

$language_choice = isset($_GET['lang']) ? $_GET['lang'] : '';
    switch ($language_choice) {
        case "en":
            $lang = 'en';
            break;
        case "fr":
            $lang = 'fr';
            break;
        case "es":
            $lang = 'es';
            break;
        default:
            $lang = $locale->default_language;
            break;
    }
	if (isset($_GET['lang'])){
	$_SESSION['user_language_choice'] = $_GET['lang'];
}

The language arrays

$lang_info_h1 = array(
	'en' => 'Browser Language Information',
	'fr' => 'Information sur la langue du navigateur',
	'es' => 'Idioma Navegador de Información',
	);

$hello_world = array(
	'en' => 'Hello World',
	'fr' => 'Bonjour tout le monde',
	'es' => 'Hola Mundo',
);

The user switches the language via a link

<ul>
	<li><a title="English" href="?lang=en">English</a></li>
	<li><a title="Français" href="?lang=fr">Français</a></li>
	<li><a title="Español" href="?lang=es">Español</a></li>
</ul>

To render the variables as HTML

echo "<h1>".$lang_info_h1[$lang]."</h1>";
echo "<p>".$hello_world[$lang].".</p>";