Skip to content

Instantly share code, notes, and snippets.

@ionrock
Created October 21, 2011 05:52
Show Gist options
  • Save ionrock/1303189 to your computer and use it in GitHub Desktop.
Save ionrock/1303189 to your computer and use it in GitHub Desktop.
there was a couple logic errors. Here is a working version with some tests.
<?php
class IPRange {
private $BITS = 256;
public function __construct($start, $end) {
$this->start = $start;
$this->end = $end;
}
public function contains($ip) {
$total = $this->ip_as_num($ip);
return ($this->start < $total) && ($total < $this->end);
}
public function ip_as_num($ip) {
$parts = array_map("intval", array_reverse(explode('.', $ip)));
$total = 0;
foreach ($parts as $power => $value) {
$total = $total + ($value * pow(256, $power));
}
return $total;
}
}
class GeoIpLookup {
private $fname = "IpToCountry.csv";
public $db = array();
public $country_db = array();
public function __construct() {
$this->load_db();
}
public function load_db() {
$handle = fopen($this->fname, 'r');
while ( !feof($handle) ) {
$line = fgets($handle);
if (strpos($line, '#') === false && $line) {
$parts = explode(',', $line);
$country = $parts[5];
$this->db[$country][] = new IPRange(intval(substr($parts[0], 1, -1)),
intval(substr($parts[1], 1, -1)));
if (!array_key_exists($country, $this->country_db)) {
if (isset($parts[6])) {
$this->country_db[$country] = $parts[6];
} else {
$this->country_db[$country] = $country;
}
}
}
}
fclose($handle);
}
public function find_country_by_ip($ip_addr) {
foreach ($this->db as $country => $ranges) {
foreach ($ranges as $range) {
if ($range->contains($ip_addr)) {
return $this->country_db[$country];
}
}
}
return $match;
}
}
// test range
$ip = '74.125.224.115';
$expected = 1249763443;
$range = new IPRange(1, 10);
$actual = $range->ip_as_num($ip);
if ($actual !== $expected) {
echo "ERROR getting ip as a number\n";
echo "$actual != $expected\n";
} else {
$iplookup = new GeoIpLookup();
$tests = array("google.com" => "74.125.224.114",
"bbc.co.uk" => "212.58.241.131");
foreach ($tests as $domain => $ip) {
echo $domain . " is from " . $iplookup->find_country_by_ip($ip) . "\n";
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment