zoukankan      html  css  js  c++  java
  • php 处理网站访问日志

    <?php
    $r = tail('dd.ddmap.log','Baiduspider');
    echo '<pre>';
    print_r($r);
    echo '</pre>';
    /**
     * @param $filename
     * @param false $num
     * @param int $n
     * @param int $base
     * @return array
     */
    function tail(string $filename,string $type = 'false',int $n = 500 , int $base=5) : array
    {
        $fp = fopen($filename,'r+');
        assert($n>0);
        $pos = $n+1;
    //    fseek($fp, -0,SEEK_END) ;
    //    $pos =  ftell($fp) / 5;
        $lines = array();
        while(count($lines) <=$n){
            try{
                fseek($fp,-$pos,SEEK_END);
            } catch (Exception $e){
                fseek(0);
                break;
            }
            $pos *= $base;
            while(!feof($fp)){
                $res = fgets($fp);
                if(!$res)continue;
                $res = Hhandle($res,$type);
                if(!$res){continue;}
                array_unshift($lines,$res);
            }
        }
    
        return $lines;
        return array_slice($lines,0,$n);
    }
    
    /**
     * @param $str
     * @return array
     */
    function isCon(string $str,$type) : string
    {
        $spiders   = ['Googlebot', 'Baiduspider', 'Sogou', 'YodaoBot', 'YisouSpider','msnbot','baiduboxapp','QQBrowser','iPhone','Chrome','Firefox'];
        $http = [$str];
        if($type !== 'false'){
            if(strpos($str,$type)){
                return $type;
            }
            return '';
        }
        foreach($spiders as $K=>$v){
    //        $v = strtolower($v);
            if(strpos($str,$v)){
                return $v;
            }
        }
        return '';
    }
    
    /**
     * @param $log
     * @param false $type
     * @return array|void
     */
    function Hhandle(string $log, $type=false)
    {
        $req = [];
        $pattern = '/^(?P<ip>[0-9.]+) - - [(?P<time>[^]]+)]+ "GET (?P<url>[^ ]+) HTTP/1.[1|0|2]" (?P<status>[0-9.]+) (?P<size>[0-9.]+) /i';
    
        preg_match($pattern, $log, $match);
        if(empty($match))return;
        $req['http'] = $log;
        $req['reptile'] = isCon($log,$type);
        if($type !== 'false' && !$req['reptile']){
            return '';
        }
    
        $req['ip']  = $match['ip'];
        $req['time']   = $match['time'];
        $req['status'] = $match['status'];
    
    
        return $req;
    }
  • 相关阅读:
    Git 基础教程 之 解决合并冲突
    Git 基础教程 之 远程库更新到本地
    Git 基础教程 之 分支管理及策略
    Git 基础教程 之 从远程库克隆
    Git 基础教程 之 添加远程仓库
    Git 基础教程 之 远程仓库
    c++11新特性1--------------auto
    线程及线程间同步
    进程间通信---信号
    进程间通信---mmap详解(与system V ipc通信对照)
  • 原文地址:https://www.cnblogs.com/LF-place/p/14718606.html
Copyright © 2011-2022 走看看