How to keep file to 1000 lines with Linux or PHP?

By : cwd

I have a file that I'm using to log IP addresses for a client. They want to keep the last 500 lines of the file. It is on a Linux system with PHP4 (oh no!).

I was going to add to the file one line at a time with new IP addresses. We don't have access to cron so I would probably need to make this function do the line-limit cleanup as well.

I was thinking either using like exec('tail [some params]') or maybe reading the file in with PHP, exploding it on newlines into an array, getting the last 1000 elements, and writing it back. Seems kind of memory intensive though.

What's a better way to do this?


Per @meagar's comment below, if I wanted to use the zip functionality, how would I do that within my PHP script? (no access to cron)

if(rand(0,10) == 10){
 shell_exec("find . logfile.txt [where size > 1mb] -exec zip {} \;")

Will zip enumerate the files automatically if there is an existing file or do I need to do that manually?

By : cwd

The fastest way is probably, as you suggested, to use tail:

passthru("tail -n 500 $filename");

(passthru does the same as exec only it outputs the entire program output to stdout. You can capture the output using an output buffer)


I agree with a previous comment that a log rotate would be infinitely better... but you did state that you don't have access to cron so I'm assuming you can't do logrotate either.


This would be the "proper" answer, and it's not difficult to set this up either.


You may get the number of lines using count(explode("\n", file_get_contents("log.txt"))) and if it is equal to 1000, get the substring starting from the first \n to the end, add the new IP address and write the whole file again. It's almost the same as writing the new IP by opening the file in a+ mode.

By : Ivan

This video can help you solving your question :)
By: admin