I'm writing a PHP script and the script outputs a simple text file log of the operations it performs. How would I use PHP to delete the first several lines from this file when it reaches a certain file size?
Ideally, I would like it to keep the first two lines (date/time created and blank) and start deleting from line 3 and delete X amount of lines. I already know about the filesize()
function, so I'll be using that to check the file size.
Example log text:
*** LOG FILE CREATED ON 2008-10-18 AT 03:06:29 ***
2008-10-18 @ 03:06:29 CREATED: gallery/thumbs
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9423.JPG to gallery/IMG_9423.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9188.JPG to gallery/IMG_9188.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9236.JPG to gallery/IMG_9236.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9228.JPG to gallery/IMG_9228.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_3104.JPG to gallery/IMG_3104.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/First dance02.JPG to gallery/First dance02.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/BandG02.JPG to gallery/BandG02.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/official03.JPG to gallery/official03.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/Wedding32.JPG to gallery/Wedding32.jpg
2008-10-18 @ 03:08:03 RENAMED: gallery/Gettaway car16.JPG to gallery/Gettaway car16.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Afterparty05.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9254.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9175.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/official05.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/First dance01.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Wedding29.jpg
2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/men walking.jpg
If you can run a linux command, try
split
. It allows you to split by line count to make things easy.Otherwise, I'm thinking you'll have to read it in and write to 2 other files.
Typical operating systems don't provide the capability to insert or delete content of a file "in-place". What you will need to do is write a function that reads the first file, and creates a new output file containing the lines you want to keep. Then when you're done, delete the old file and rename the new one to the old name.
In pseudocode:
The advantage of this method over some of the other ones presented is that it doesn't require you to read the whole file into memory first. You didn't mention how large your upper size limit was, but if it's something like 100 MB you might find that loading the file into memory is not an acceptable use of space.
edit: with correction from by rcar and saving the first line.