How to parse Apache logs using a regex in PHP

后端 未结 4 616
终归单人心
终归单人心 2021-02-09 17:00

I\'m trying to split this string in PHP:

11.11.11.11 - - [25/Jan/2000:14:00:01 +0100] \"GET /1986.js HTTP/1.1\" 200 932 \"http://domain.com/index.html\" \"Mozill         


        
4条回答
  •  眼角桃花
    2021-02-09 17:42

    Here is some Perl, not PHP, but the regex to use is the same. This regex works to parse everything I've seen; clients can send some bizarre requests:

    my ($ip, $date, $method, $url, $protocol, $alt_url, $code, $bytes,
            $referrer, $ua) = (m/
        ^(\S+)\s                    # IP
        \S+\s+                      # remote logname
        (?:\S+\s+)+                 # remote user
        \[([^]]+)\]\s               # date
        "(\S*)\s?                   # method
        (?:((?:[^"]*(?:\\")?)*)\s   # URL
        ([^"]*)"\s|                 # protocol
        ((?:[^"]*(?:\\")?)*)"\s)    # or, possibly URL with no protocol
        (\S+)\s                     # status code
        (\S+)\s                     # bytes
        "((?:[^"]*(?:\\")?)*)"\s    # referrer
        "(.*)"$                     # user agent
    /x);
    die "Couldn't match $_" unless $ip;
    $alt_url ||= '';
    $url ||= $alt_url;
    

提交回复
热议问题