Question

I would like an automatic language selection in my index.php. When the user is from Columbia he is redirected to index_columbia.html and other countries to index_english.html.

How can I make this with PHP?

Was it helpful?

Solution

The language information which is sent by the browser is with server reserved variables. Well, this solution is not based on the location of the visitor but the language setting of the browser which seems better. If doesn't matter if the visitor is from Columbia or France if he is using English as a language its better to show him the English version of the website.

You can use $_SERVER['HTTP_ACCEPT_LANGUAGE'] like this:-

<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
    case "fr":

        include("index_fr.php");
        break;
    case "it":

        include("index_it.php");
        break;
    case "en":

        include("index_en.php");
        break;        
    default:

        include("index_en.php");
        break;
}
?>

OTHER TIPS

You can check by IP address (there are webservices for it). e.g.: http://freegeoip.net/

Also you can use the accept-language header sent by the browser. http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 This can be retrieved from the $_SERVER variable.

You can use a country lookup by IP address.

A class that does this can be found at http://www.phpandstuff.com/articles/geoip-country-lookup-with-php.

You can use my code:

$langs = array('en','fr','de');
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
if (!in_array($lang, array_keys($langs))) $forward = 'index_'.$lang.'.html';
else $forward = 'index_en.html';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top