Steven
Steven

Reputation: 25284

How to detect a user's language through their IP Address

I have developed a website www.tenxian.com.

It has three language versions, English, Japanese and Chinese. How can I write an effective PHP program which can automatically choose a language version based on the IP address of the visitor?

If I use "if-else", the code would be much complicated; If I use switch-case, how to write it since the data which should be dealt with are IP ranges, not particular numbers. Besides, I don't know these IP ranges

What is the easiest way to do it?

Upvotes: 7

Views: 21290

Answers (8)

take a look at the maxmind geoip module for PHP (http://www.maxmind.com/app/php), as for your data structure perhaps key it to the ISO-3166-1 country code which apache_note("GEOIP_COUNTRY_CODE"); returns.

Upvotes: 0

Amad
Amad

Reputation: 31

<?php
$ln = split(",",$_SERVER["HTTP_ACCEPT_LANGUAGE"]);
print_r($ln[0]);
?>

Upvotes: 2

Chris
Chris

Reputation: 8968

Yes please don't do it... Google does this and dreaking annoying.. I always get the thai version instead the english one from my browser.

Use the http headers from the browser.

Upvotes: 2

deceze
deceze

Reputation: 522016

Please, PLEASE, do not make the mistake of thinking that IP == language. Look at the browsers accept-language header first, then the browser identification string which might contain the OS language, and only then take the IP into account. In almost 100% of all cases the browser accept-language header will be present and sufficient.

And always give the user the choice to switch to another language.

Just apart from the simple case of a foreigner abroad, how do you determine the language for Belgium, where they speak French, Dutch and German? (Maybe that doesn't apply to your case, but just philosophically. :)).

Upvotes: 27

Aishwar
Aishwar

Reputation: 9714

Assuming you can convert IP ranges to one of your language choices, you could do this (all replies above): have all your messages in the applications stored in an associative array of this form.

$MESSAGES[$USER_LANGUAGE][$msgId]

where $USER_LANGUAGE can be chinese, japanese, or english (or any other equivalent enum). $msgId can be things like "login.successful", "login.fail" etc. Where ever you display messages to the user do not display hardcoded strings, make a reference to the variable using the $msgId.

You can access it as a global variable OR you can create a function that takes in the $msgId as a parameter and returns the message, $USER_LANGUAGE can be a global variable as well (which is set the first time the user comes in).

Upvotes: 0

Amber
Amber

Reputation: 526573

You'd probably want to use some form of IP geocoding database (example).

Upvotes: 0

ghoppe
ghoppe

Reputation: 21784

Perhaps this will help: www.countryipblocks.net

Upvotes: 0

Xorlev
Xorlev

Reputation: 8643

Check out GeoPlugin:

http://www.geoplugin.com/webservices/php

Upvotes: 2

Related Questions