PHP language detection

PHP How to detect the browser language from client?

When you want to provide multiple languages support on you website, you will need to find a simple way to change the default languageof your page based on the language of the browser of your client. If you are facing this problem, their is how I manage that on this website:

<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
    case "fr":
        echo "PAGE FR";
        //include("index_fr.php");//include check session FR
        break;
    case "it":
        echo "PAGE IT";
        //include("index_it.php");
        break;
    case "en":
        echo "PAGE EN";
        //include("index_en.php");
        break;        
    default:
        echo "PAGE EN - Setting Default";
        //include("index_en.php");//include EN in all other cases of different lang detection
        break;
}
?>

Going further

If you want to keep the language information all along the user session, you could use the php-session variable $_SESSION or cookies. In my case, I prefer the php-session. You can also change this setting using a $_POST input:

<?php
//Load or create session
session_start();

if ( !isset($_SESSION['lang']) ){
   $_SESSION['lang'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
} elseif ( isset($_POST['lang_fr_x']) ){
	$_SESSION['lang'] = 'fr';
} elseif ( isset($_POST['lang_it_x']) ){
	$_SESSION['lang'] = 'it';
} elseif ( isset($_POST['lang_en_x']) ){
	$_SESSION['lang'] = 'en';
}

switch ( $_SESSION['lang'] ){
    case "fr":
        echo "<h1>Selectionnez votre langue :</h1>";
        break;
    case "it":
        echo "<h1>Seleziona la tua lingua :</h1>";
        break;
    default:
        echo "<h1>Select your language:</h1>";
        break;
}
?>

<form method="post">
	<input type="image" src="img/fr.svg" width="64px" height="48px" title="Fran&ccedil;ais" name="lang_fr" alt="Fr"/>
	<input type="image" src="img/it.svg" width="64px" height="48px" title="Italiano" name="lang_it" alt="It"/>
	<input type="image" src="img/us.svg" width="64px" height="48px" title="English" name="lang_en" alt="En"/>
</form>

Then you just need to add session_start(); at the beginning of your script to load the $_SESSION variable.