• Edit
  • Delete

php parse apache logs including the date

<?php

$dir = '/var/log/apache2';
$allFiles = scandir($dir);

$goodFiles = [];

foreach($allFiles as $file) {
    if (strstr($file, 'example-access.log')) {
        $goodFiles[] = $file;
    }
}

natsort($goodFiles);

$output = [];

foreach($goodFiles as $file) {
    $lines = gzfile($dir . '/' . $file);
    foreach ($lines as $line) {
        $output[] = $line;
            
        // parse log
        $regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/';
        preg_match($regex ,$line, $matches);
        // 1 = IP 4 = date 5=time 6=timezone 8=url 10=httpcode
        var_dump($matches);
            
        // parse date 
        $datestr = "{$matches[4]} {$matches[5]}{$matches[6]}";
        $datearr = date_parse_from_format('d/M/Y H:i:sP', $datestr);
        $dateiso = "{$datearr['year']}-{$datearr['month']}-{$datearr['day']} {$datearr['hour']}:{$datearr['minute']}:{$datearr['second']}";
        var_dump($date)
    }
}

// newest on bottom;
$output = array_reverse($output);

var_dump($output);