Skip to content

Instantly share code, notes, and snippets.

@speeddragon
Created September 30, 2016 23:36
Show Gist options
  • Save speeddragon/61e9be983ec47ecf2aaf4a898151cd5c to your computer and use it in GitHub Desktop.
Save speeddragon/61e9be983ec47ecf2aaf4a898151cd5c to your computer and use it in GitHub Desktop.
Convert CSV to MySQL database for MaxMind GeoLite2
<?php
function calculateEndIp($startIp, $mask) {
if (($min = ip2long($startIp)) !== false) {
$max = ($min | (1<<(32-$mask))-1);
$address = long2ip($max);
return $address;
}
}
// Read country to memory
$countryIds[] = array();
$csvFile = file('country.csv');
foreach ($csvFile as $line) {
$data = str_getcsv($line);
if ($data[4] == 'ES' || $data[4] == 'PT') {
// 49518,en,AF,Africa,RW,Rwanda
$countryIds[$data[0]] = $data[4];
}
}
print_r($countryIds);
// Read IP
$validIpList = array();
$csvFile = file('ip.csv');
foreach ($csvFile as $line) {
$data = str_getcsv($line);
if (isset($countryIds[$data[1]])) {
// 1.0.0.0/24,2077456,2077456,,0,0
$beginIp = explode('/', $data[0]);
$mask[$beginIp[1]] = true;
$endIp = calculateEndIp($beginIp[0], $beginIp[1]);
$beginIp = $beginIp[0];
$validIpList[] = array($beginIp, $endIp, $countryIds[$data[1]]);
}
}
print_r($validIpList);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment