Log file viewer in PHP

  1. <?php
  2. // Author : Hemanth.HM
  3. // Purpose : To view log file on the browser.
  4.  
  5. function tail($file, $num_to_get=10)
  6. {
  7. $fp = fopen($file, 'r');
  8. $position = filesize($file);
  9. fseek($fp, $position-1);
  10. $chunklen = 4096;
  11. while($position >= 0)
  12. {
  13. $position = $position - $chunklen;
  14. if ($position < 0) { $chunklen = abs($position); $position=0;}
  15. fseek($fp, $position);
  16. $data = fread($fp, $chunklen). $data;
  17. if (substr_count($data, "\n") >= $num_to_get + 1)
  18. {
  19. preg_match("!(.*?\n){".($num_to_get-1)."}$!", $data, $match);
  20. return $match[0];
  21. }
  22. }
  23. fclose($fp);
  24. return $data;
  25. }
  26.  
  27. function show_log($log){
  28. $data=tail('$log');
  29. $data = explode("\n",$data);
  30. while (list($var, $val) = each($data)) {
  31. ++$var;
  32. $val = trim($val);
  33. print "$val <br />";
  34. }
  35. print "<hr>";
  36. }
  37.  
  38. <html>
  39. <body>
  40. <b>Click on the links to see the logs</b><br>
  41. <hr>
  42. <a href="?run=elog">Apache-Access-Log</a>
  43. <br>
  44. <a href="?run=aerr">Apache-Error-Log</a>
  45. <br>
  46. <a href="?run=0">Clear</a>
  47. <br>
  48. <hr>
  49. </body></html>
  50. <?php
  51. if (isset($_GET['run'])) $linkchoice=$_GET['run'];
  52. else $linkchoice='';
  53.  
  54. switch($linkchoice){
  55.  
  56. // Give path to log file as per your log requirement, must be have // proper permissions set for www-data group to read the log
  57.  
  58. case 'alog' :
  59. show_log('/var/log/apache2/access.log');
  60. break;
  61.  
  62. case 'aerr' :
  63. show_log('/var/log/apache2/error.log');
  64. break;
  65.  
  66. }
  67.  
  68. ?>
Share this