PHP 가 큰 파일 을 읽 고 보 여 주 는 간단 한 인 스 턴 스(추천)

4158 단어 php읽 기문건
PHP 로 로그 파일 을 읽 습 니 다.파일 이 클 때 메모리 가 부족 합 니 다.따라서 지정 한 줄 의 데 이 터 를 부분적으로 읽 고 읽 어야 합 니 다.

PHP 코드:

<?php
class Test{
  //    
  const LOG_PATH="E:\phpServer\Apache\logs\error.log";
  const NGINX_LOG_PATH="E:\phpServer\
ginx\logs\error.log"; // const PAGES=50; public static function main(){ header("content-type:text/html;charset=utf-8"); if(!empty($_GET['action'])){ self::$_GET['action'](); exit; } } public static function showApacheLogs(){ $test=new Test(); $result=$test->readLogs(self::LOG_PATH,self::PAGES); $html=""; foreach($result as $line){ if(strpos($line,"error:")){ $line="<font color='red'>".$line."</font>"; } $html.="<div class='line'>".$line."<div>"; } echo $html; } public static function showNginxLogs(){ $test=new Test(); $result=$test->readLogs(self::NGINX_LOG_PATH,self::PAGES); $html=""; foreach($result as $line){ if(strpos($line,"error")){ $line="<font color='red'>".$line."</font>"; } $html.="<div class='line'>".$line."<div>"; } echo $html; } /** * */ private function readLogs($filePath,$num=20){ $fp = fopen($filePath,"r"); $pos = -2; $eof = ""; $head = false; // Num , $lines = array(); while($num>0){ while($eof != "
"){ if(fseek($fp, $pos, SEEK_END)==0){ //fseek 0, -1 $eof = fgetc($fp); $pos--; }else{ // , , $pos fseek($fp,0,SEEK_SET); $head = true; // , break; } } array_unshift($lines,fgets($fp)); if($head){ break; } // , , , $eof = ""; $num--; } fclose($fp); return array_reverse($lines); } } Test::main(); ?> <style type="text/css"> *{ padding: 0; margin: 0; } .logsBox{ margin:5px; padding: 5px; width: 600px; background: #000; color:#fff; font-size: 13px; float: left; } .logsBox .line{ margin: 12px 0; } </style> <div class="logsBox apache"> <div class="line"> ...</div> </div> <div class="logsBox nginx"> <div class="line"> ...</div> </div> <script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(function(){ function showLogs(api,showClass){ function readLogs(){ $.ajax({ url:api, type:"get", dataType:"text", success:function(data){ $(showClass).html(data); } }); } readLogs(); setInterval(readLogs,5000); } showLogs("?action=showNginxLogs",".nginx"); showLogs("?action=showApacheLogs",".apache"); }); </script>
이상 의 PHP 에서 큰 파일 을 읽 고 보 여 주 는 간단 한 인 스 턴 스(추천)는 바로 작은 편집 이 여러분 에 게 공유 하 는 모든 내용 입 니 다.참고 가 되 고 저 희 를 많이 사랑 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기