PHP 8.5.0 Beta 3 available for testing

Voting

: two plus zero?
(Example: nine)

The Note You're Voting On

lucky at somnius dot com dot ar
19 years ago
Jim's (jim at lfchosting dot com) code for the last-line issue is perfect if the file is not empty, or moreover if it has more than one line. However if the file you're using cotains no new-line character at all (i.e. it is empty or it's got one line and only one) the while loop will stuck indefinitely.

I know this script is meant for big files which would always contain at least several lines, but it would be clever to make the script error-proof.

Thus, here's a little modification to his code.

<?php
function readLastLine ($file) {
$fp = @fopen($file, "r");

$pos = -1;
$t = " ";
while (
$t != "\n") {
if (!
fseek($fp, $pos, SEEK_END)) { // *** - fseek returns 0 if successfull, and -1 if it has no succes as in seeking a byte outside the file's range
$t = fgetc($fp);
$pos = $pos - 1;
} else {
// ***
rewind($fp); // ***
break; // ***
} // ***
}
$t = fgets($fp);
fclose($fp);
return
$t;
}
?>

Lines added and/or modified have been marked with "// ***". I hope this helps!

Regards!

<< Back to user notes page

To Top