470,850 Members | 1,233 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,850 developers. It's quick & easy.

manage a text log file of 10 lines

1,584 Expert 1GB
Hey guys,

I need to maintain short list of messages in a text log file. I was just googling for the best way to delete the first or last line and insert a new one.

Basically with each access I'll delete a line from the top (or bottom could work too) and insert a new line at the other end. (so it scrolls basically)

If your curious, this is the status of a daily cron job, I basically want to know the status up to the last 10 days.

I'm not asking for code, but something pretty light. (ie if I decided i wanted 100 or 300 lines). Most of you know my PHP skills and know I can just put it in an array and rewrite to the file after I'm done, but

can this be done in two lines of code and accessing the file resource only once (ie one file handle).

hope that makes enough sense, I'll post the code once I have something,


Apr 8 '09 #1
3 1580
1,654 Expert 1GB
I could not understand the requirements completely, but I would suggest this solution. I hope it matches your requirements.
Expand|Select|Wrap|Line Numbers
  1. file_put_contents(
  2.     $file_name,
  3.     preg_replace(
  4.         "/^[^\n]+\n/",
  5.         "",
  6.         file_get_contents($file_name).$new_line
  7.     )
  8. );
If I didn't get it right, let me know.

Apr 10 '09 #2
511 Expert 256MB
get all your file contents to an array. if you want to skip line 1, print array starting from element 2. (or use array_pop). the manual documents array functions so check the manual.
Apr 11 '09 #3
6,050 Expert 4TB
Obviously storing the messages at the bottom makes more sense and, in my head, seems easier to edit.

You can use file() to return the lines of a file into an array.

Let us know how you get along with this, Dan.

- mark.
Apr 11 '09 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

22 posts views Thread by Ling Lee | last post: by
10 posts views Thread by ross | last post: by
3 posts views Thread by Wade G. Pemberton | last post: by
7 posts views Thread by Chris | last post: by
6 posts views Thread by ivan.perak | last post: by
9 posts views Thread by =?Utf-8?B?QnJpYW4gQ29vaw==?= | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.