使用PHP讀取日志文件,當文件比較大的時候,會報內存不足,因此應該部分讀取,讀取指定的行數的數據
PHP代碼:
<?php class Test{ //日志路徑 const LOG_PATH="E:\phpServer\Apache\logs\error.log"; const NGINX_LOG_PATH="E:\phpServer\\nginx\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 != "\n"){ 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 讀取大文件並顯示的簡單實例(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持。