I want to track the country of the visitors and then redirect them to appropriate subdomains of my site like what google does...
And upto what extent i can rely on the data of the api if i should use any?..
I'm using php..
Download and install Maxmind's GeoLite Country database, which claims 99.5% accuracy. You can pay to upgrade to a paid version with a claimed 99.8% accuracy. There are four options with respect to how to use the database from PHP:
All these options has a method for getting a country code. I won't include SQL option, but you can get more info here.
Pure PHP4:
include("geoip.inc");
$gi = geoip_open("/usr/local/share/GeoIP/GeoIP.dat",GEOIP_STANDARD);
$code = geoip_country_code_by_addr($gi, "24.24.24.24");
PECL PHP extension:
$code = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
Apache module:
$code = apache_note("GEOIP_COUNTRY_CODE");
You can then redirect based on these codes, using an HTTP redirect:
$redirect = array("AU" => "http://australia.example.com", "NZ" => "http://newzealand.example.com")
$url = $redirect[$code]
header("Location: $url");
This causes two HTTP requests however, and is thus suboptimal. A better approach is to use the Apache module to do rewriting, in your .htaccess
file:
GeoIPEnable On
GeoIPDBFile /path/to/GeoIP.dat
# Redirect one country
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^CA
RewriteRule ^(.*)$ http://www.canada.com$1 [L]
# Redirect multiple countries to a single page
RewriteEngine on
RewriteCond %{ENV:GEOIP_COUNTRY_CODE} ^(CA|US|MX)$
RewriteRule ^(.*)$ http://www.northamerica.com$1 [L]
Of course, an arguably better way to do this is to get someone else to do it for you, at the DNS level. A quick search revealed this company, (I have no idea if they are good or not) no doubt there are others. This is how Google does it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With