Hack63.Find Out Where Your Guests Are Coming From


Hack 63. Find Out Where Your Guests Are Coming From

Use the Net-Geo PEAR module to tell you where in the world the people surfing to your site are coming from.

Have you ever wondered where the guests to your site are coming from? It turns out that finding out is not as tough as you might think. First, the IP address of every incoming request is provided to you through the Apache request handler. Second, a simple PEAR library is available that will turn an IP address into a physical location. This hack will show you how it all works.

6.14.1. The Code

Save the code in Example 6-41 as geo.php.

Example 6-41. An IP-to-geography converter
 <html> <body> <?php require_once( "cache/lite.php" ); require_once( "net/geo.php" ); $ip = $_SERVER['REMOTE_ADDR']; $ip = "64.246.30.37"; $geo = new Net_Geo(); ?> <table> <tr><td>IP</td><td><?php echo( $ip ); ?></td></tr> <tr><td>City</td><td><?php echo( $res['CITY'] ); ?></td></tr> <tr><td>State</td><td><?php echo( $res['STATE'] ); ?></td></tr> <tr><td>Country</td><td><?php echo( $res['COUNTRY'] ); ?></td></tr> <tr><td>Latitude</td><td><?php echo( $res['LAT'] ); ?></td></tr> <tr><td>Longitude</td><td><?php echo( $res['LONG'] ); ?></td></tr> </table> </body> </html> 

This is about as simple as it gets. Require the correct PHP and PEAR modules, and all you need is the Net_Geo( ) function. You can break up the returned object into city, state, country, latitude, and longitude, all through simple parameters.

6.14.2. Running the Hack

For starters, you need the Net-Geo PEAR module [Hack #2]. Install that and surf on over to geo.php; you should see something like Figure 6-33.

How cool is that? Now I know the city, state, and country of the request. And even the latitude and longitude. With that information, I can plot all the requests on a map and see where everyone is coming from graphically.

6.14.3. See Also

  • "Create Custom Google Maps" [Hack #95]

Figure 6-33. The geographical location of the request




PHP Hacks
PHP Hacks: Tips & Tools For Creating Dynamic Websites
ISBN: 0596101392
EAN: 2147483647
Year: 2006
Pages: 163

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net