1

Hi I want as the title says change the language of the site using a button but this without altering the url mywebsite.com (Without doing mywebsite.com?lang=es) by just changing PHP variables in this code:

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


if($xlang == "es")
{
$g_lang = "es";
}
else if ($xlang == "en")
{
$g_lang = "en";
}
else
{
$g_lang = "en";
}

And then using this button

<a class="langx" href="#"></a>

Change the language without altering the url

Is there a way to do that? if so, how?

Thanks in advance.

AbsoluteƵERØ
  • 7,816
  • 2
  • 24
  • 35
Joscplan
  • 1,024
  • 2
  • 15
  • 35
  • `$_SERVER['HTTP_ACCEPT_LANGUAGE']` is set by the browser. You will need to use cookies, and then `$_COOKIES['lang']`. – Dave Chen Jun 15 '13 at 00:49
  • And then you modify the cookies via JS or what? – Joscplan Jun 15 '13 at 00:53
  • No, the server reads the cookies, and based on them, outputs the correct localization. – Dave Chen Jun 15 '13 at 00:54
  • And then how do you change them later? – Joscplan Jun 15 '13 at 00:55
  • 1
    Using the button as described above, the button will have to be wrapped in a `form` and hidden values to send the desired language. – Dave Chen Jun 15 '13 at 00:56
  • With that, the server will change the cookie, and the correct language will be outputted the next time the user uses the website. – Dave Chen Jun 15 '13 at 00:57
  • Something I ran into on this myself a couple of weeks ago, when you use something like `substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)` you're only capturing the preferred language. If they're let's say Chinese, then `CN` would be the first even though `EN` might by a close runner up in regard to user preference. – AbsoluteƵERØ Jun 15 '13 at 02:53
  • I've added an answer with my reasoning and some of my own code for catching languages. – AbsoluteƵERØ Jun 15 '13 at 03:26

3 Answers3

3

You need to send the required value to the server when the button is clicked, so your link would have to have the language string like ?lang=es.

Then you can process it on the server side and store the language for the current visitor in for example a database (for logged-in users), a session or a cookie.

Then you can use a header redirect to redirect the user to the site without the language string and check at the top if the db-entry / session / cookie is set and use that language.

jeroen
  • 91,079
  • 21
  • 114
  • 132
  • `Without doing mywebsite.com?lang=es`? Potentially, you could have a small form, a hidden value that specifies which language, and then have the form post. – Dave Chen Jun 15 '13 at 00:49
  • @DaveChen If you redirect after setting the language, the url in the browser address bar will never show the language string (which I assume the OP is after). But like I said, you need to get the information to the server with the button. You could use an ajax post, but that does not offer any advantages except that you exclude non-javascript visitors. – jeroen Jun 15 '13 at 00:50
  • As @DaveChen I need it to be without "lang=es" using JS or something. – Joscplan Jun 15 '13 at 00:52
  • The reason one would want to avoid setting the language with the `$_GET` is that, if someone sends you a URL, they can change your language without you knowing. – Dave Chen Jun 15 '13 at 00:52
  • @DaveChen True, but like I said, I read the question as showing the url without showing a language string. There could be other interpretations as the question does not leave that very clear. – jeroen Jun 15 '13 at 00:54
  • +1 so you know I have no hard feelings. Maybe the OP wants to do this on the page itself? I agree this question isn't explained properly. – Dave Chen Jun 15 '13 at 00:56
  • As I said in the question, change the language without altering the url itself and using $_GET. – Joscplan Jun 15 '13 at 00:57
  • 1
    @DaveChen Thanks! To be honest, I think the only realistic scenario is for logged-in users, for a public page this would lead to search engine trouble. – jeroen Jun 15 '13 at 00:58
  • @JoseCardama Read my answer, the url does not change. And whether you use GET or POST for a language selection is not really an issue, it's hardly a secret. – jeroen Jun 15 '13 at 01:00
  • +1 its a good simple way to do , @DaveChen op needs to check either by geo location or let the user select manually and for manually.. an to select manually he needs to do what Jeroen telling – NullPoiиteя Jun 15 '13 at 01:04
2

While you can handle the request dynamically, you need to provide another method, and here's why. According to Google if you care anything about SEO, you'll want to Make sure the page language is obvious. You can do the hat trick on the fly and switch the language via language preferences, but you also need to provide a link to a page that is always in the other language if you expect to get any traffic in that language from search engines.

If this page dynamically detects the language, then whatever language Google sees when it crawls is the language it will make the page as.

http://www.example.com/

If the site contains a query string flag for another language the site is likely to be crawled in both languages IF there is a link to the second language somewhere on your site. These are good examples (a separate domain is the best option) for showing Google where a Spanish page would reside.

http://es.example.com - best for SEO

http://www.example.com/?lang=es

http://www.example.com/es/

In your PHP code you're only catching the initial 2 digit code for the preferred language of the browser. Some people actually read in more than one language (basically anyone who's not American). They might have those other languages in their preferred languages, so while someone from France may have fr as their preferred language, they may also understand English (en), so their browser accepted string might look something like this in Chrome:

fr,en-US;q=0.8,en;q=0.6

or this in IE:

fr-FR,en-US;q=0.5

This code will check to see if they've set the $_GET flag for the language and override the automatic translation. I found this code, then modified it to work for my purposes because the site where it's being used is European where most people speak multiple languages. For this code I've modified it here, so if their preferred language isn't Spanish it will default to English. This would go into a file like lang.php which would get included on every page.

<?php
$langs = array();
if (!empty($_GET['lang'])){
    $tempLang = $_GET['lang'];
        //Setup the switch for all of the possible languages.
    switch($tempLang){
        case 'es':
        $pref='es';
        break;
        default:
        //english
        $pref='en'; 
    }

} elseif (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
    // break up string into pieces (languages and q factors)
    preg_match_all('/([a-z]{1,8}(-[a-z]{1,8})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/i', $_SERVER['HTTP_ACCEPT_LANGUAGE'], $lang_parse);

    if (count($lang_parse[1])) {
        // create a list like "en" => 0.8

         $langs = array_combine($lang_parse[1], $lang_parse[4]);

        // set default to 1 for any without q factor
        foreach ($langs as $lang => $val) {
            if ($val === '') $val = 1;
        $lParse = strtolower(preg_replace('!\-.*$!','',$lang));
            if(!isset($newLangs[$lParse])){
                $newLangs[$lParse] = $val;
            }

        }

        // sort list based on value 
        arsort($newLangs, SORT_NUMERIC);
    }

//Set the preferred languages for the website (available translations)
$preferred = array('en','es');

//Check for overlap keeping the preference order
$intersect = array_values(array_intersect(array_keys($newLangs), $preferred));

//print_r($newLangs);

if(isset($intersect[0])){
    //Set the first preference
    $pref = $intersect[0];  
    if(preg_match('!^es!',$pref)){
        $pref='es';
    }   
} else {
    //default to english
    $pref = 'en';   
}


} else {
    //default to english
    $pref = 'en';   
}

?>

On the page including lang.php you would need to check the $pref variable to show the proper translation for the language.

Javascript

You can do a redirect with Javascript to make the page load the other language using this same code, however search engines typically only look at Javascript for exploits and won't follow the links in the Javascript. According to Google Webmaster's Guidelines:

Use a text browser such as Lynx to examine your site, because most search engine spiders see your site much as Lynx would. If fancy features such as JavaScript, cookies, session IDs, frames, DHTML, or Flash keep you from seeing all of your site in a text browser, then search engine spiders may have trouble crawling your site.

You can do the change with a click using AJAX, however the URL where AJAX would listen would need to be passed the parameter and these are usually passed via $_GET variables.

IP Look-up

Another method some people have tried is to check the IP address and reverse look-up the location to see where the country of origin is, then they'll pick the national language. The problems with this are:

  1. People travel
  2. Some IP addresses are registered to owners in other countries (think corporate blocks) rather than the country where the user is browser.
  3. Some of the IP address listings are highly inaccurate.

Cookies

Not all users accept cookies and some corporate firewalls may even strip the cookies.

AbsoluteƵERØ
  • 7,816
  • 2
  • 24
  • 35
0

i don't understand what do you need to do exactly , but i think you want to refresh a page to apply changes when you click the button without adding anything to your url ! if i'm right , you can use Jquery location.reload() function like this :

// don't forget to add link to jquery file for example : <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript">

  $(document).ready(function(){
   $('.langx').click(function() {

          location.reload();

   });
  });

</script>

personally i use gettext library to translate my website: i make a list of languages and then i use ajax call to send what user are choosing as language and if translation for this choice is available i return ok and finally i reload the page with js. you can learn about gettext lib or check documentation here

if this is not what do you want, please add more details to render clear your question

medBouzid
  • 7,484
  • 10
  • 56
  • 86