Parse Apache log in PHP using preg_match

后端 未结 5 1071
日久生厌
日久生厌 2020-12-23 14:34

I need to save data in a table (for reporting, stats etc...) so a user can search by time, user agent etc. I have a script that runs every day that reads the Apache Log and

5条回答
  •  不思量自难忘°
    2020-12-23 14:56

    To parse an Apache access_log log in PHP you can use this regex:

    $regex = '/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) "([^"]*)" "([^"]*)"$/';
    preg_match($regex ,$log, $matches);
    

    To match the Apache error_log format, you can use this regex:

    $regex = '/^\[([^\]]+)\] \[([^\]]+)\] (?:\[client ([^\]]+)\])?\s*(.*)$/i';
    preg_match($regex, $log, $matches);
    $matches[1] = Date and time,           $matches[2] = severity,
    $matches[3] = client addr (if present) $matches[4] = log message
    

    It matches lines with or without the client:

    [Tue Feb 28 11:42:31 2012] [notice] Apache/2.4.1 (Unix) mod_ssl/2.4.1 OpenSSL/0.9.8k PHP/5.3.10 configured -- resuming normal operations
    [Tue Feb 28 14:34:41 2012] [error] [client 192.168.50.10] Symbolic link not allowed or link target not accessible: /usr/local/apache2/htdocs/x.js
    

提交回复
热议问题