Thursday, October 29, 2009

read the last line of a file in PHP

If your not a gh33k just move along.
move along, this is not the post you are looking for.

Had a hard to track down bug today where some code that was supposed to return the last line of a log file failed - the logs had recently been rotated and the new file had no lines in it yet. I modified it to create a pointer to the beginning of the file and break out of the infinite loop if the pointer cursor ever gets back to the beginning of the file. With a few minor changes it will work in C C++ C# or Java as they all have something similar to fseek, ftell fclose etc

* Reads the last line of a, presumably large, logfile
* without loading the whole file into memory
* Safe to use for 0 or 1 line files
* @param string
* @return string
function readlastline($fileName)

$fp = @fopen($fileName, "r");
$begining = fseek($fp, 0);
$pos = -1;
$t = " ";
while ($t != "\n") {
fseek($fp, $pos, SEEK_END);
if(ftell($fp) == $begining){
$t = fgetc($fp);
$pos = $pos - 1;
$t = fgets($fp);
return $t;


Fusion said...

It's all gr33k to me...

xl said...

tail -n1 filename

unique_stephen said...

Fusion > like totally l33t

XL > From within PHP? The security risk of accessing the shell from within a web accessible script gives me the hebbies.

Spiky Zora Jones said...



just saying. :)

Anonymous said...

I read it anyway.
I wish I had listened to you.

white rabbit said...

Erm righty...

Glad you cleared that one up.

Memphis Steve said...

I was about to say, looks like C. I haven't seen C in a long, long time. Right now I'm mucking through a Microsoft world thanks to a web app that suddenly cant' seem to return data from the database. It spins and spins along, and then after wasting much time, suddenly wants me to log in again. I changed nothing. It worked fine before. It had been running in production for months. WTF?

Steph said...

You just leveled up to a whole new platform of Geekdom. Well done yourself.

Anonymous said...

As you say, im movin on cause I dont get the code.. Iv been known to speak in code, even a little Greek nt Geek, but I will be back on another day..

De Campo said...