manage a text log file of 10 lines

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    manage a text log file of 10 lines

    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,


    Thanks




    Dan
  • hsriat
    Recognized Expert Top Contributor
    • Jan 2008
    • 1653

    #2
    I could not understand the requirements completely, but I would suggest this solution. I hope it matches your requirements.
    Code:
    file_put_contents(
        $file_name,
        preg_replace(
            "/^[^\n]+\n/",
            "",
            file_get_contents($file_name).$new_line
        )
    );
    If I didn't get it right, let me know.

    Cheers.

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      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.

      Comment

      • Markus
        Recognized Expert Expert
        • Jun 2007
        • 6092

        #4
        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.

        Comment

        Working...