doudong1117 2012-11-14 14:21
浏览 375
已采纳

使用PHP从日志文件中提取数据

I have a server log file from which I am trying to create a PHP page which summaries the data it stores. Each record in the log is stored on a new line, and in the format:

207.3.35.52 -- [2007-04-01 01:24:42] "GET index.php HTTP/1.0" 200 11411 "Mozilla/4.0"

//ip -- [timestamp] "GET url HTTP/1.0" status code bytes "user agent".

I am trying to write a summary which displays: the total amount of requests, the total amount of requests form the articles directory, the total bandwidth consumed and finally the amount of 404 errors and their pages.

PHP:

$handle = fopen('logfiles/april.log','r') or die ('File opening failed');
$requestsCount = 0;
    while (!feof($handle)) {
        $dd = fgets($handle);
        $requestsCount++;   
        $parts = explode('"', $dd);
        $statusCode = substr($parts[2], 0, 4);
        }
fclose($handle);

This code opens the file and counts the amount of records, seperates and finds the status code number in the record. When echoing $statusCode it does show the correct information, showing all the status codes in the log.

A function which accepts two arguements to total the 404 errors:

function requests404($l,$s) {
        $r =  substr_count($l,$s);
        return "Total 404 errors: ".$r."<br />";
}

Echo the result:

echo requests404($statusCode, '404');

This function doesn't work, it just returns 0. Working with txt files in PHP is my weakest skill and I would really appreciate some help as I think I may be going about it the complete wrong way. Thanks.

  • 写回答

3条回答 默认 最新

  • dongshengyin0147 2012-11-14 14:32
    关注
    $handle = fopen('logfiles/april.log','r') or die ('File opening failed');
    $requestsCount = 0;
    $num404 = 0;
    
    while (!feof($handle)) {
        $dd = fgets($handle);
        $requestsCount++;   
        $parts = explode('"', $dd);
        $statusCode = substr($parts[2], 0, 4);
        if (hasRequestType($statusCode, '404')) $num404++;
    }
    
    echo "Total 404 Requests: " . $num404 . "<br />";
    fclose($handle);
    
    function hasRequestType($l,$s) {
            return substr_count($l,$s) > 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀