Hey guys I need some assistance with a php regex problem. Regex might not even be the best method to use here. I do not know how to use php at all – I just surf around looking at examples and try to paste them together to accomplish what I need done.
My current code looks like this…
// full path to text file
define("TEXT_FILE", "cports.log");
// number of lines to read from the end of file
define("LINES_COUNT", 5);
function read_file($file, $lines) {
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
break;
}
$t = fgetc($handle);
$pos --;
}
$linecounter --;
if ($beginning) {
rewind($handle);
}
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
}
fclose ($handle);
return array_reverse($text);
}
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
echo $line;
}
?>
It basically reads a file named cports.log and tails the last 5 lines. However an example of my log file looks like this…
1/27/2013 7:16:06 PM Added {92.255.176.84}
1/27/2013 7:16:07 PM Removed {92.255.176.84}
1/27/2013 7:16:08 PM Added {176.15.101.53}
1/27/2013 7:16:09 PM Removed {176.15.101.53}
1/27/2013 7:16:23 PM Added {98.119.183.235}
1/27/2013 7:16:24 PM Removed {98.119.183.235}
1/27/2013 7:16:27 PM Added {37.251.51.9}
1/27/2013 7:16:28 PM Removed {37.251.51.9}
1/27/2013 7:16:38 PM Added {92.255.176.84}
1/27/2013 7:16:38 PM Added {82.112.38.83}
1/27/2013 7:16:39 PM Removed {92.255.176.84}
1/27/2013 7:16:39 PM Removed {82.112.38.83}
1/27/2013 7:16:45 PM Added {74.61.121.147}
1/27/2013 7:16:50 PM Removed {74.61.121.147}
So the output of my php file is just the last 5 lines of the log file. But what I need done is take each IP nested in the brackets and either store them into an array or a variable to be used in this section of code…
<?php
require_once("geoipcity.inc");
$ip = "8.8.8.8";
$gi = geoip_open("GeoLiteCity.dat", GEOIP_STANDARD);
$record = geoip_record_by_addr($gi, $ip);
echo "Location One <br>";
echo "Country: " .$record->country_name . "<br>";
echo "City: " .$record->city . "<br>";
echo "Latitude: " .$record->latitude . "<br>";
echo "Longitude: " .$record->longitude . "<br>";
geoip_close($gi);
?>
This block of code is basically iterated 5 times to print out the geolocation of 5 IPs from whatever $ip is. Any help would be much appreciated! Once again I don’t know php so please be patient with me. 🙂
First tip would be using the
file()function to read a file line-wise, then you can just iterate over them:But using a regex you could read the file at once and have
preg_match_allextract all IPs in one swoop:With a nicely structured file like that, you can even completely arraytize all columns at once, using