对apache访问日志的条件过滤以及统计

     遇到这样的事情,公司在别的网站投放了广告(比如搜狐),点击广告连接到我们自己的网站 ,广告是按点击量收费的。所以,公司要求我们自己做个后台统计点击统计量!           

        想想通过统计apache的访问日志,可以完成这件事情;        

       前台页面代码:

 

        // 时间转化函数

      function Format2UnixTime ($str)
             {
            $time = $str;
            $time = str_replace("/"," ",$time);
            $time_array = explode( ":",$time,2);
            $time = $time_array[0]." ".$time_array[1];
            return strtotime($time);
             }

             $lines = file ('/logs/access_log');   //日志文件目录,windows下是access.log

            $i=0;   //声明变量

             foreach ($lines as $line_num => $line) {
                        if (preg_match ("/sohu/i",strtolower($line))) {     //过滤   (参看下面日志)
                                if (!preg_match ("/slurp/",strtolower($line))){
                                              preg_match("/([0-9.]+)?([ -]+)?(/[)?([0-9a-zA-Z+: //]+)?(/])?( /"GET //)?([a-z0-9A-Z.///?&=%_/-:+]+)?( HTTP//1.[1|0|2]/" )?([0-9.]+)?( )?([0-9./-]+)?( /")?([a-z0-9A-Z.///?&=%_/-:+]+)?(/" /")?(.*)/i",$line, $matches);
                                              $formatTime = Format2UnixTime($matches[4]);
                                              $access_time=strftime(" %Y-%m-%d %H:%M:%S " ,$formatTime);

                                                if(strtotime("$access_time")>=strtotime("$start_time") &&strtotime("$access_time") <= strtotime("$end_time") ){                          //取某段时间的日志信息
               
                                          if($matches[7] == "hello.htm"){           //点击广告,访问我们自己的网站页面;
                
              echo "".$matches[1]."".$access_time."".$matches[7]."".$matches[9]."".$matches[13]."";               
                 }
                               $i++;
                                  
                       
                }
                        }
                        }
             
              
      }

  echo "点击次数:  ".$i;

?> 
    

日志:

21.1.208.174 - - [04/May/2008:13:27:48 +0800] "GET /hello.htm HTTP/1.1" 200 14312    "http://www.sohu.com/" "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)"
//这是日志的内容 ,显示的格式我们可以在http.config中定义;

//上面的日志告诉我们在 2008年5月4日 ,ip地址21.1.208.174 点击了我们在sohu上投放的广告,访问我们的页面hello.htm;

日志过滤:

因为如果将所有的访问日志都放在一个日志文件中,那么这个日志文件将很大;

如果我们需要的访问日志放到一专门的文件中,那么将给我们带来方便;

如何做呢? apache文档中告诉我们了,使用SetEnvIf ;

我们在http.config文件中,加入

SetEnvIf Referer www/.sohu/.com test 
CustomLog logs/sohu_log common env=test

上面的代码表示,如果请求的url是www.sohu.com  那么,我们将这个访问日志放到test_log 中;

如果想在加几个过滤条件:

SetEnvIf Referer www/.sohu/.com test
SetEnvIf Referer www/.sina/.com test
CustomLog logs/test_log common env=test

上面代码表示 如果请求url 是搜狐或者新浪 都放到那个日志文件中;

 

你可能感兴趣的:(对apache访问日志的条件过滤以及统计)