Here is a handy function for reading a file line by line in reverse (from the end of the file).
function rfgets($handle) {
$line = null;
$n = 0;
if ($handle) {
$line = '';
$started = false;
$gotline = false;
while (!$gotline) {
if (ftell($handle) == 0) {
fseek($handle, -1, SEEK_END);
} else {
fseek($handle, -2, SEEK_CUR);
}
$readres = ($char = fgetc($handle));
if (false === $readres) {
$gotline = true;
} elseif ($char == "\n" || $char == "\r") {
if ($started)
$gotline = true;
else
$started = true;
} elseif ($started) {
$line .= $char;
}
}
}
fseek($handle, 1, SEEK_CUR);
return strrev($line);
}
$filename = 'top-1m.csv';
echo "Reverse reading $filename" . PHP_EOL;
$handle = @fopen($filename, 'r');
for ($i = 0; $i < 10; $i++) {
$buffer = rfgets($handle);
echo $buffer . PHP_EOL;
}
fclose($handle);
The output produced (from the Alexa top 1 million domains list) is:



