| > Projects > PHP > IP to Country Lookup |
PHP > IP to Country Lookup
Sometimes we need to know where a user is from to better deliver content to them. Web sites accomplish this by one of a few ways (I'm only showing the one). The best and most reliable way is by using the user's IP Address.
This PHP class is cake to implement and even easier to use. Were using a freely available database which is constantly updated. So why pay for a service like this when you can get it for free. It's a no-brainer. Enough of my rambling, so let's jump right into it.
Setup
- Download the netblocks database here which is made freely available by WebHosting.Info: http://ip-to-country.webhosting.info/downloads/ip-to-country.csv.zip (Mirror Feb-12-08)
- Using phpMyAdmin, execute the following SQL to create the required table:
CREATE TABLE netblocks
(
BlockStart VARCHAR(10) NOT NULL,
BlockEnd VARCHAR(10) NOT NULL,
Prefix1 VARCHAR(2) NOT NULL,
Prefix2 VARCHAR(3) NOT NULL,
Country VARCHAR(100) NOT NULL,
PRIMARY KEY (BlockStart,BlockEnd)
) ENGINE=InnoDB;
- Import the Zip file, select CSV for format and set the "Fields terminated by" to a comma (,) and click Go.
- Include the class below in your scripts and call it using something along these lines:
<?php
require_once 'class.iplookup.php';
// Create DB connection
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('iplook', $conn);
$lookup = new IPLookup($conn);
$country = $lookup->fetch('24.79.93.165');
if ($country)
echo "Hello, we see that your from " . $country['Country'] . "!";
// prints "Hello, we see that your from Canada!"
?>
- And your done!
class.iplookup.php
<?php
/**
* IPLookup
*
* Translates an IP Address to a country code
*
* @author Mike Frank <mike@eyesis.ca>
* @version 1.0
* @link http://www.eyesis.ca/projects.html
* @param Resource $link MySQL Link Resource
* @param String $table Optional. The table
where the netblocks are locate (default 'netblocks')
* @return Boolean False if an error occurred
*/
class IPLookup
{
public $link, $table;
public function __construct($link, $table = 'netblocks')
{
$this->link = $link;
$this->table = $table;
}
/**
* fetch
* Queries the database with a IP Address and returns the Country
*
* @param String $ip Optional. IP Address to
resolve (default is remote address)
* @return Boolean An error occurred
* @return Array Associate array of the country details
*/
public function fetch($ip = '')
{
if (!$ip)
$ip = $_SERVER['REMOTE_ADDR'];
$result = mysql_query("SELECT * FROM " . $this->table . " WHERE "
. "INET_ATON('".trim($ip)."') BETWEEN BlockStart and "
. "BlockEnd LIMIT 1", $this->link);
if (mysql_num_rows($result) < 1)
return false;
else
return mysql_fetch_assoc($result);
}
}
?>
|