PHP GeoIP Primer Tutorial

PHP GeoIP Primer Tutorial

PHP GeoIP Primer Tutorial

Today, we wanted to enter the world of GeoIP, which, as the name suggests, is gleaning information about the “where” of life given an …

  • IP address … known directly … or discernible via a …
  • domain or host name

… making use of databases provided by the great MaxMind open source resource we established an account with, allowing us to download database CSV data (for our desires) that is updated on a regular basis.

Originally we thought we’d be using PHP to host Python …


# getting us, on AlmaLinux, installing via ...
$ dnf list *geo*ip*
$ dnf install python3-geoip2
$ pip install python-geoip
$ pip install python-geoip-geolite2
$ pip3 install maxminddb
$ pip3 install maxminddb-geolite2

… and then register with MaxMind after this, to help make this solution happen, but ended up combining the (just) PHP supervision of …

  • ping … means (via PHP shell_exec), as required, to derive an IP address from a host or domain name … then …
  • PHP … means by which MaxMind CSV files are scoured to link IP address to geodata of interest, to derived City and Country of interest information

… via a first draft …


<?php
// geoip_hostname.php
// RJM Programming
// September, 2024
// Thanks to GeoIP

$city='';
$country='';
$state='';
$ccode='';
$tzplace='';
$continent='';
$newhname='';
$preresults='';
$results='';
$hname='';
$via='';
if (isset($_GET['via']) || isset($_POST['via'])) {
$via='' . (isset($_GET['via']) ? str_replace('+',' ',urldecode($_GET['via'])) : '') . (isset($_POST['via']) ? str_replace('+',' ',urldecode($_POST['via'])) : '');
}
if (isset($_GET['hostname']) || isset($_POST['hostname'])) {
$hname='' . (isset($_GET['hostname']) ? str_replace('+',' ',urldecode($_GET['hostname'])) : '') . (isset($_POST['hostname']) ? str_replace('+',' ',urldecode($_POST['hostname'])) : '');
if ($via == $hname) { $via=''; }
}

if (trim($hname) != '') {
if (substr(trim($hname),0,1) < '0' || substr(trim($hname),0,1) > '9') {
if (strpos($hname, '//') === false) {
$hname='http://' . $hname;
} else if (strpos($hname, ':') === false) {
$hname='http:' . $hname;
}
//$bigcont=file_get_contents($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'ip_example.py');
//file_put_contents('/tmp/ip_example_ours.py', str_replace(explode("'", explode("url = '", $bigcont)[1])[0], $hname, $bigcont));
//echo '/usr/bin/python ' . $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'test_geoip.py --hostname=' . $hname;
//exit;
if (1 == 1) {
$results=shell_exec('ping -c 4 ' . str_replace('http://','',$hname));
} else {
$results=shell_exec('/usr/bin/python ' . $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'test_geoip.py --hostname=' . str_replace('http://','',$hname));
}
if (strpos($results, 'PING ' . str_replace('http://','',$hname) . ' (') !== false) {
$newhname=explode(" ",explode(")",trim(explode('PING ' . str_replace('http://','',$hname) . ' (', $results)[1]))[0])[0];
$results='';
} else if (strpos($results, 'IP address:') !== false) {
$newhname=explode(" ",explode("\n",trim(explode('IP address:', $results)[1]))[0])[0];
$results='';
}
} else if ($hname != '') {
if ($via != '' && (substr(trim($via),0,1) < '0' || substr(trim($via),0,1) > '9')) {
$preresults='Looking up ' . $via . " ( " . $hname . " ) ";
} else {
$preresults='Looking up ' . $hname;
}
$gnames=',';
foreach (glob('/tmp/GeoLite2-City-CSV_20240920/GeoLite2-City-Blocks-IP*.csv') as $fname) {
$fgc='';
if (1 == 1) {
$fgc="\n" . shell_exec('fgrep "' . $hname . '/" ' . $fname) . "\n";
} else {
$fgc="\n" . file_get_contents($fname) . "\n";
}
$listis="\n" . $fgc . "\n";
if (strpos($listis, "\n" . $hname . "/") !== false) {
$lis=explode("\n" . $hname . "/", $listis);
for ($ii=1; $ii<sizeof($lis); $ii++) {
$cols=explode(',',$lis[$ii]);
if ($cols[1] != '') {
if (strpos($gnames, ',' . $cols[1] . ',') === false) {
$gnames.=$cols[1] . ',';
}
}
}
}
}
if ($gnames != ',') {
$garr=explode(',', substr($gnames,1,(-2 + strlen($gnames))));
foreach (glob('/tmp/GeoLite2-City-CSV_20240920/GeoLite2-City-Locations-*.csv') as $fname) {
for ($jj=0; $jj<sizeof($garr); $jj++) {
$fgc='';
if (1 == 1) {
$fgc="\n" . shell_exec('fgrep "' . $garr[$jj] . '," ' . $fname) . "\n";
} else {
$fgc="\n" . file_get_contents($fname) . "\n";
}
$listis="\n" . $fgc . "\n";
if (strpos($listis, "\n" . $garr[$jj] . ",") !== false) {
$lis=explode("\n" . $garr[$jj] . ",", $listis);
for ($ii=1; $ii<sizeof($lis); $ii++) {
$cols=explode(',',$lis[$ii]);
if ($cols[3] != '') {
if ($ccode == '') { $ccode='<table border=1 style=width:80%;><tr><td>'; }
$ccode.=' ' . str_replace('"','',$cols[3]) . '</td><td>';
}
if ($cols[4] != '') {
if ($country == '') { $country='<table border=1 style=width:80%;><tr><td>'; }
$country.=' ' . str_replace('"','',$cols[4]) . '</td><td>';
}
if ($cols[9] != '') {
if ($city == '') { $city='<table border=1 style=width:80%;><tr><td>'; }
$city.=' ' . str_replace('"','',$cols[9]) . '</td><td>';
}
if ($cols[6] != '') {
if ($state == '') { $state='<table border=1 style=width:80%;><tr><td>'; }
$state.=' ' . str_replace('"','',$cols[6]) . '</td><td>';
}
if ($cols[11] != '') {
if ($tzplace == '') { $tzplace='<table border=1 style=width:80%;><tr><td>'; }
$tzplace.=str_replace(' NA',' ',' ' . str_replace('"','',$cols[1])) . '</td><td>';
}
if ($cols[2] != '') {
if ($continent == '') { $continent='<table border=1 style=width:80%;><tr><td>'; }
$continent.=' ' . str_replace('"','',$cols[2]) . '</td><td>';
}
}
}
}
$results="<br><br>City: " . ($city == '' ? $city : $city . '</td></tr></table>') . "\nState: " . ($state == '' ? $state : $state . '</td></tr></table>') . "\nCountry: " . ($country == '' ? $country : $country . '</td></tr></table>') . "\nCountry Code: " . ($ccode == '' ? $ccode : $ccode . '</td></tr></table>') . "\nContinent: " . ($continent == '' ? $continent : $continent . '</td></tr></table>') . "\nTimezone: " . ($tzplace == '' ? $tzplace : $tzplace . '</td></tr></table>') . "<br><br>";
}
}
}
}

echo "<html>
<head>
<title>Hostname Lookup geoip_hostname.php - RJM Programming - September, 2024</title>
</head>
<body onload=\" if (document.getElementById('hostname').value != '') { setTimeout(function() { document.getElementById('blook').click(); }, 2000); } \">
<h1>Hostname Lookup</h1>
<h3>RJM Programming - September, 2024 ... thanks to <a target=_blank title=MaxMind href='//www.maxmind.com/'>MaxMind</a></h3>
<div id=results>" . $preresults . str_replace("\n","<br>",$results) . "</div><br><br>
<form method=POST action=./geoip_hostname.php>
<input style=width:80%; type=text name=hostname id=hostname placeholder='Enter host name or domain name or host IP address to show information regarding ...' value='" . $newhname . "'></input><br><br>
<input type=hidden name=via id=via value='" . $hname . "'></input>
<input type=submit id=blook value=Lookup></input>
</form>
</body>
</html>";

exit;
?>

… in a first draft GeoIP using PHP web application you can also try below

If this was interesting you may be interested in this too.

This entry was posted in eLearning, Tutorials and tagged , , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *