[PHP] reads and displays large files,
When using PHP to read log files, when the file is large, it will report insufficient memory. Therefore, you should partially read and read the data of the specified number of rows.
PHP code:
<? Phpclass Test {// Log Path const LOG_PATH = "E: \ phpServer \ Apache \ logs \ error. log "; const NGINX_LOG_PATH =" E: \ phpServer \ nginx \ logs \ error. log "; // number of lines displayed 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 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;}/*** read log */private function readLogs ($ filePath, $ num = 20) {$ fp = fopen ($ filePath, "r"); $ pos =-2; $ eof = ""; $ head = false; // when the total number of rows is less than Num, determine whether the first line has reached $ lines = array (); while ($ Num> 0) {while ($ eof! = "\ N") {if (fseek ($ fp, $ pos, SEEK_END) = 0) {// return 0 if fseek is successful, -1 $ eof = fgetc ($ fp); $ pos --;} else {// when the first line arrives, set $ pos to fail fseek ($ fp, 0, SEEK_SET); $ head = true; // when the file header is reached, enable break;} array_unshift ($ lines, fgets ($ fp); if ($ head) {break;} // This sentence can only be put after the previous sentence, because after the file header is reached, read the first line and then jump out of the entire loop $ 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"> log reading... </div> <div class = "logsBox nginx"> <div class = "line"> log reading... </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) {response (showclass).html (data) ;}});} readLogs (); setInterval (readLogs, 5000);} showLogs ("? Action = showNginxLogs ",". nginx "); showLogs ("? Action = showApacheLogs ",". apache ") ;}); </script>