Skip to content

Instantly share code, notes, and snippets.

@ain ain/log.php
Created Feb 23, 2012

What would you like to do?
tail functionality in PHP
// full path to text file
define("TEXT_FILE", "/home/www/default-error.log");
// number of lines to read from the end of file
define("LINES_COUNT", 10);
function read_file($file, $lines) {
//global $fsize;
$handle = fopen($file, "r");
$linecounter = $lines;
$pos = -2;
$beginning = false;
$text = array();
while ($linecounter > 0) {
$t = " ";
while ($t != "\n") {
if(fseek($handle, $pos, SEEK_END) == -1) {
$beginning = true;
$t = fgetc($handle);
$pos --;
$linecounter --;
if ($beginning) {
$text[$lines-$linecounter-1] = fgets($handle);
if ($beginning) break;
fclose ($handle);
return array_reverse($text);
$fsize = round(filesize(TEXT_FILE)/1024/1024,2);
echo "<strong>".TEXT_FILE."</strong>\n\n";
echo "File size is {$fsize} megabytes\n\n";
echo "Last ".LINES_COUNT." lines of the file:\n\n";
$lines = read_file(TEXT_FILE, LINES_COUNT);
foreach ($lines as $line) {
echo $line;

This comment has been minimized.

Copy link
Owner Author

ain commented Feb 23, 2012


This comment has been minimized.

Copy link

sinrise commented Jul 28, 2014

This helped me make a nice little improvement to my error log display, as well as make it easier to extend it's features. Thanks!


This comment has been minimized.

Copy link

okothomondi commented May 25, 2017

wat if i dont specify the number of line in define("LINES_COUNT", 10); instead just get whole file

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.