0

I have a file that updates itself by appending, however this file becomes huge (500MB). I would like to read the last 50 lines in the file. How can this be done?

dukevin
  • 22,384
  • 36
  • 82
  • 111

2 Answers2

4

Tail -n50 will return the last 50 lines of the file.

$filename = 'test.html';
$output = shell_exec('exec tail -n50 ' . $filename);
echo $output;

Therefore, you don't have to load the entire file in memory.

Edit:

If you want to echo "<br>" after each line you do:

echo str_replace(PHP_EOL, '<br />', $output);
Book Of Zeus
  • 49,509
  • 18
  • 174
  • 171
  • However, be careful that $filename isn't something malicious. – someone Sep 03 '11 at 00:22
  • Yes if the purpose of reading the file is not for internal use. In that case, you can always remove bad characters (using regexp), check if the file exists (file_exists) and check if it's readable (is_readable) before you load check the last 50 lines. I strongly recommend security if this your case. – Book Of Zeus Sep 03 '11 at 00:26
  • that looks like a really nice solution, one question though, how can I get a `
    ` after each line?
    – dukevin Sep 03 '11 at 00:35
  • I updated my code. Read about PHP_EOL @ http://stackoverflow.com/questions/128560/when-do-i-use-the-php-constant-php-eol – Book Of Zeus Sep 03 '11 at 00:37
3

You'll need to use fseek to move the file pointer a certain number of bytes from the end of the file:

$fp = fopen('myfile','r');
fseek($fp,-1024, SEEK_END);
$last_kb_of_file = fgets($fp,1024);

You'll have to tell fgets how many bytes you want to read, not how many lines. It has no idea what the format of the file is. You'll have to split the result on a newline and see if you have 50 lines.

Christopher Armstrong
  • 7,907
  • 2
  • 26
  • 28