1

I have to make a script that tails the last 10 lines of a screenlog.0 file in Ubuntu. The problem is that no matter what I try doing myself I end up failing. However, when I was searching for an alternative scripted by someone else, a more experienced developer, I found this: https://gist.github.com/karabanov/3818740

It is a nice piece of code that doesn't use much memory. My problem is that I don't know how to make it retrieve only the last 10 lines of the file. It retrieves all of them and that's something I really want to avoid.

Could you explain my what I need to modify in the code in order to make it work how I need it to work? Or maybe you have better scripts. Any help is appreciated.

P.S: I am a newbie PHP developer and I started working with PHP few months ago. I need this script in order to display the console for each game server in my game panel project.

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
GMBeniamin
  • 119
  • 1
  • 6
  • 12
  • Why not use `tail -10`? My guess is that it wouldn't be accepted as solution to your homework... – Ulrich Eckhardt Jan 20 '18 at 13:50
  • Can't you use `shell_exec("tail -n 10 /path/to/your/file")` ? – Syscall Jan 20 '18 at 13:51
  • As I commented in the answer bellow: using this command made my browser freeze. But thank you for your comment. :) – GMBeniamin Jan 20 '18 at 14:39
  • Possible duplicate of [What is the best way in PHP to read last lines from a file?](https://stackoverflow.com/questions/15025875/what-is-the-best-way-in-php-to-read-last-lines-from-a-file) – Blue Feb 02 '18 at 00:26

1 Answers1

4

using that library is an overkill, the simple tail command will work fine in ubuntu

tail -n 10 /you/file/full/path/here

if you want to get this from within a php script you can use

$string = exec( 'tail -n 10 /you/file/full/path/here');
Nathanael
  • 870
  • 5
  • 11
  • 2
    `exec` only returns the last line of the output. You probably want ``$string = shell_exec('tail -n 10 '.$filename);`` - also worth noting that it uses the current working directory as a base, so you don't necessarily need the full path. – Niet the Dark Absol Jan 20 '18 at 14:07
  • Thank you! I tried this few days ago and it all went good but after a while the browser kept freezing. The game console gets many lines of text and I think that is the problem. When I tried to above library everything worked smoothly. Is there a way to keep the browser from freezing? – GMBeniamin Jan 20 '18 at 14:38
  • For those not having `exec` available by the server (e.g. renting restricted virtual server), this [tail php](https://tekkie.dev/php/tail-functionality-in-php#tail-in-php) script could become handy. – Ain Tohvri Nov 17 '20 at 19:58