yusufiqbalpk
yusufiqbalpk

Reputation: 272

How to retrieve city and country through IP address in PHP

I am trying to make a log of users heading to my website. I want to save their IP addresses, as well as city and country info.

Thanks in Advance.

Upvotes: 0

Views: 4687

Answers (4)

Sumant
Sumant

Reputation: 964

I Think you should go for Google analytic, All these data you will get from there. Otherwise for ip address you can use this script

function getIP() {
$ip;
if (getenv("HTTP_CLIENT_IP"))
$ip = getenv("HTTP_CLIENT_IP");
else if(getenv("HTTP_X_FORWARDED_FOR"))
$ip = getenv("HTTP_X_FORWARDED_FOR");
else if(getenv("REMOTE_ADDR"))
$ip = getenv("REMOTE_ADDR");
else
$ip = "UNKNOWN";
return $ip;
}

& for country name

http://geoip.wtanaka.com/cc/$ipaddr

this will return country ISO code.

Upvotes: 1

Ignas
Ignas

Reputation: 1965

Try using MaxMind GeoIP database which I find the best solution that's freely available. It has a set of methods to retrieve the city and the country by IP and to get the ip just use: $_SERVER['REMOTE_ADDR']

Upvotes: 2

Andrius Naruševičius
Andrius Naruševičius

Reputation: 8578

Do the users input their City and Country? If yes then easily save the data to database.

Or do you want to track these by IP? If this one - download/buy the database of the countries by ip from http://www.ip2country.net/download.html and only put the IP into the database.

Upvotes: 0

danneth
danneth

Reputation: 2783

You can get the IP from $_SERVER['REMOTE_ADDR']. To get location you will have to find some service that provides lookup and check the IP you just collected.

You might also consider signing up for Google analytics.

Upvotes: 1

Related Questions