Question

How can you apply a US style for people in US and a UK style for people in UK?

For example, I want to change a flag according to the user's location in my site.

Was it helpful?

Solution

First, you need to find your visitor's IP address. It will be in the $_SERVER['REMOTE_ADDR'] global variable. You can then look this IP up against a database of IP to country mappings to get the country code for the IP.

This method is not 100% accurate, but it is "good enough" for most uses, and more importantly it is fast. You will probably want to cache the country code in a cookie to avoid repeated lookups, if you expect high traffic.

One such mapping can be found here: http://software77.net/cgi-bin/ip-country/geo-ip.pl

A PHP class that takes an IP and returns a country code using a bundled mapping file: http://www.phpclasses.org/browse/package/2363.html

OTHER TIPS

If you really want the user's location, the keyword is geolocation.

For your purpose, however, you can just check $_SERVER["ACCEPT_LANGUAGE"]. The syntax is a little bit complex. Fortunately, virtually every client does what should have been done right away and orders the preferred locations. So, calculate stripos($_SERVER["ACCEPT_LANGUAGE"], $lang) for all locales $lang (like "en-us") you do support and take the lowest, discarding locales that yield false.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top