0

This is the insert into file, it puts 1 row at a time. I want to read only last 10 rows, for example.

$file = SITE_ROOT."logs/log.txt";

        if ($handle = fopen($file, 'a+b')) {
            $content = Session::get('username') . " has logged out on - " . datetime_to_text("now") . "\r\n";
            fwrite($handle, $content);
            fclose($handle);
        } else {
            echo 'Culd not open file for writing.';
        }

this is how i read them, reads them all.

$file = SITE_ROOT . "logs/log.txt";
                                $content = "";
                                if ($handle = fopen($file, 'r')) {
                                    while (!feof($handle)) {
                                        $content .= '<li><a href="#">' . fgets($handle) . '</a></li>';
                                        echo count($handle);
                                    }
                                    fclose($handle);
                                }

                                echo nl2br($content);

How to read only 10?

Done, i found the answer i was looking for.

Thx, i found useffull this one.



$file = SITE_ROOT . "logs/log.txt";
$data = array_slice(file($file), -10);
$data1 = file($file);
foreach ($data as $line) {
echo '<li><a href="#">'. nl2br($line) . '</a></li>';
}
xttrust
  • 585
  • 1
  • 4
  • 15
  • possible duplicate of [Tailing Log File and Write results to new file](http://stackoverflow.com/questions/16892270/tailing-log-file-and-write-results-to-new-file) – Baba Jun 11 '13 at 23:19

1 Answers1

0
 while (!feof($handle)) {

is the line actually "reading" the line so change it to this

$i=0;
$max=10;
while (!feof($handle) && ($i++ < $max)) {

that sets a counter and counts until $max is hit. Sorry I missed the last 10. Only seen the 10 lines between the code blocks

How to read only 5 last line of the text file in PHP?

Gives great info for last x lines

Community
  • 1
  • 1
exussum
  • 18,275
  • 8
  • 32
  • 65