Getting country by IP based on GeoLite
For a global application I needed some way to determine the country of the visitor. A couple of years ago I used a similar solution but that database was not available anymore. The guys at Maxmind however publish a free, yes free geoIP database every month and according to them it has an accuracy of 98% procent.So what I did was rewrite my original component so now it is speaking to this new database from Maxmind. Here are the steps to make this work for you!
First download the geoIP Lite datbase from Maxmind. (CSV format)
Import this into your favorite database, mine is MSSQL. Maxmind has different links to examples on how to do this.
Name the table "geoip" and the columns "begin_ip,end_ip,begin_num,end_num,country,name", and make sure that if you are using MSSQL that the _num columns are of datatype BIGINT.
After that copy/paste the following component and save this as geoip.cfc
<cfcomponent>
<cffunction name="ip2country" access="remote" returntype="query">
<cfargument name="ip" required="yes" type="string">
<cfset var q = "">
<cfset Aip = ListToArray(arguments.ip,'.')>
<cfset Aip = ((Aip[1] * 16777216) + (Aip[2] * 65536) + (Aip[3] * 256) + (Aip[4]))>
<cfquery name="q" datasource="-- YOUR DSN ---">
SELECT country,name
FROM geoip
WHERE begin_num <= <cfqueryparam cfsqltype="CF_SQL_BIGINT" value="#Aip#">
AND end_num >= <cfqueryparam cfsqltype="CF_SQL_BIGINT" value="#Aip#">
</cfquery>
<cfreturn q>
</cffunction>
</cfcomponent> After that make a test page with this code in it. If all goes well it should display the country that your are currently in.
<cfinvoke component="geoip" method="ip2country" returnvariable="qCountry">
<cfinvokeargument name="ip" value="#cgi.remote_addr#" />
</cfinvoke>
<cfdump var="#qCountry#"> To make it a bit easier to import this database I have made a download available for you guys and gals in a normal TXT format. A what the heck.. the complete code is in the download.
6455 viewed | 3 opinion(s) | del.icio.us | Digg it | Tjarko @ 20/06/07 11:01 cet


