Skip to content

Instantly share code, notes, and snippets.

@gnovaro
Last active May 16, 2024 11:16
Show Gist options
  • Save gnovaro/0b739fe03d07da03fb79f2bcf7dea72e to your computer and use it in GitHub Desktop.
Save gnovaro/0b739fe03d07da03fb79f2bcf7dea72e to your computer and use it in GitHub Desktop.
Tail log php
<?php
/**
* Error Log Tail
* @author Gustavo Novaro
* @version 1.0.3
* Set in php.ini error_log=
*/
// Linux Path
$log_path = '/var/log/php_error.log';
// Windows path
//$log_path = 'C:\Windows\Temp\php_error.log';
function tail($filename, $lines = 40, $buffer = 4096)
{
// Open the file
if(!file_exists($filename))
die('No such file: '.$filename);
$f = fopen($filename, "rb");
// Jump to last character
fseek($f, -1, SEEK_END);
// Read it and adjust line number if necessary
// (Otherwise the result would be wrong if file doesn't end with a blank line)
if(fread($f, 1) != "\n") $lines -= 1;
// Start reading
$output = '';
$chunk = '';
// While we would like more
while(ftell($f) > 0 && $lines >= 0)
{
// Figure out how far back we should jump
$seek = min(ftell($f), $buffer);
// Do the jump (backwards, relative to where we are)
fseek($f, -$seek, SEEK_CUR);
// Read a chunk and prepend it to our output
$output = ($chunk = fread($f, $seek)).$output;
// Jump back to where we started reading
fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
// Decrease our line counter
$lines -= substr_count($chunk, "\n");
}
// While we have too many lines
// (Because of buffer size we might have read too many)
while($lines++ < 0)
{
// Find first newline and remove all text before that
$output = substr($output, strpos($output, "\n") + 1);
}
// Close file and return
fclose($f);
return $output;
}
$output = tail($log_path);
$output = str_replace(' America/Argentina/Buenos_Aires','',$output);
echo "<pre>";
echo $output;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment