How to Tell Where Your Visitors are Geographically Using PHP

Posted in PEAR, php by ShortLikeAFox on September 13th, 2008

If you have a website and want to tell where your users are coming from geographically PHP and PEAR make this possible. To turn a guest’s IP into a physical location the first thing you are going to need to do is make sure that you have the Net_Geo PEAR module. If you don’t have the Net_Geo PEAR module, you are going to have to use the PEAR Package Manager to acquire it.

If you don’t think that you have access to PEAR because of your hosting package, check out this explanation on how to install PEAR on an account that doesn’t allow access by default. It is written with GoDaddy shared accounts in mind, but should work for most hosting packages that don’t come with PEAR set up.

After you have Net_Geo package installed, it only takes a few lines of code to acquire geographical data:

<?php

require_once("Net/Geo.php");
$ip = $_SERVER['REMOTE_ADDR'];
//$ip = "64.246.30.37";
$firstNetGeo = new Net_Geo();
$geoData = $firstNetGeo->getRecord($ip);

?>

IP: <?php echo($ip); ?><br/>
Latitude: <?php echo($geoData['LAT']); ?><br/>
Longitude: <?php echo($geoData['LONG']); ?>
<br/>
Country: <?php echo($geoData['COUNTRY']); ?><br/>
State: <?php echo($geoData['STATE']); ?><br/>
City: <?php echo($geoData['CITY']); ?><br/>

 

The Code At Work:

IP: 38.107.191.114

Latitude:

Longitude:

Country:

State:

City: