Question

My site have an folder language where have:

en.php

<?
$lang = array(

    'sp1' => 'Welcome',
    'sp2' => 'Home',

);
?>

and it.php

<?
    $lang = array(

        'sp1' => 'Benvenuto',
        'sp2' => 'A casa',

    );
    ?>

In the index.php i have like:

<h4><?=$lang['sp1']?></h4>
<a><u><strong><?=$lang['sp2']?></a></u></strong><br />

But this is an option for change the language from cpanel, how I can transform to the geo language.. when an italian visit my site can view my site in italian language, etc?

Was it helpful?

Solution 2

Browsers advertise the user's "preferred" language in an HTTP header called Accept-Language, which you can read in PHP as $_SERVER['HTTP_ACCEPT_LANGUAGE'].

There is actually a fairly complex structure to this header, allowing multiple languages to be given priorities, and the language itself can take a few different forms. The answers to this previous question discuss how to parse it fully.

But as a first approximation, you can just take the first two letters, which will generally be one of the ISO 639-1 codes listed here by the US Library of Congress or here on Wikipedia:

$default_language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);

However, this should never be the only way of selecting the language. As explained fairly clearly by this W3C document, the browser might not be correctly configured, or the user might not be using their own computer, so that it would not be sending the correct value.

Instead, you should treat this as a default, and allow the user to over-ride it. This can be as simple as providing links on every page which add ?lang=it (etc) to the current URL. Then set a cookie containing their preference, and ignore the accept-language from then on:

if ( $_GET['lang'] ) {
    // User asked for a particular language; obey, and remember in a cookie
    setcookie('lang', $_GET['lang'], 0, '/');
    $preferred_language = $_GET['lang'];
} elseif ( $_COOKIE['lang'] ) {
    // Cookie found from previous selection
    $preferred_language = $_COOKIE['lang'];
} else {
    // Guess based on browser settings
    $preferred_language = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
}

OTHER TIPS

You can use $_SERVER['HTTP_ACCEPT_LANGUAGE']

<?php
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
switch ($lang){
    case "fr":
        //echo "PAGE FR";
        include("fr.php");
        break;
    case "it":
        //echo "PAGE IT";
        include("it.php");
        break;
    case "en":
        //echo "PAGE EN";
        include("en.php");
        break;        
    default:
        //echo "PAGE EN - Setting Default";
        include("en.php");//include EN in all other cases of different lang detection
        break;
}
?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top