Page 1 of 1

Edit log file

Posted: Tue Jun 17, 2003 2:00 pm
by badboy
I have a rather large lof file (350 MB) which cannot be edited from my desktop.
Would it be possible to use PHP to open this file and delete certain line ?
I would like to delete all of last years entries/lines while keeping this year's ?

The file looks like this:

66.196.65.21 - - [30/Dec/2003:23:56:11 -0500] "GET /robots.txt HTTP/
66.196.72.53 - - [31/Dec/2003:00:05:04 -0500] "GET /br/cgi/
12.148.209.198 - - [01/Jan/2003:01:04:17 -0500] "GET /robots.txt HTTP/1.1" 404
12.148.209.198 - - [02/Jan/2003:01:08:17 -0500] "GET / HT

How would I go about reading the date within each line and delete lines with old/last year's date ?

Really appreciate the help !
PM

Posted: Tue Jun 17, 2003 3:46 pm
by releasedj

Code: Select all

<?php
// create file handles to old and new lof files
$file_in = fopen('oldlog.file', 'r');
$file_out= fopen('newlog.file', 'w');

// loop through old log file and write lines not in 2002
while (!feof($file_in))
{
    $line = fgets($file_in, 4096);

    // check if it's old or not
    if (preg_match('/\[[0-9]{2}\/[0-9]{2}\/2003/', $line)
    {
        fwrite($file_out, $line);
    }
}
?>
This should write a new log file, only with stuff from 2003. You should be able to then remove the old one.

I didn't test this script, and so you should run it on a test file first.

Regards,

Kelvin

Posted: Wed Jun 18, 2003 4:10 am
by twigletmac
This post has been moved to PHP - Normal as it is a 'how to' question and as such does not belong in the Advanced forum. Please ensure that you read forum descriptions before posting.

Mac

Posted: Wed Jun 18, 2003 9:39 am
by badboy
Hi Mac,

Just posted for the first time yesterday and obvioulsy did not read the rules !
Hope this message is now posting in PHP-Normal !

As for the code sample from Kelvin, can't wait to try it out.
Waiting for my Host to give me write/execute to the logs folder.

Upon examining the preg_match below:
if(preg_match('/\[[0-9]{2}\/[0-9]{2}\/2003/', $line)
is it correct for reading this date format 31/Dec/2003 ?
66.196.72.53 - - [31/Dec/2003:00:05:04 -0500] "GET /br/cgi/

or should the preg_match read like this:
if(preg_match('/\[[0-9]{2}\/[A-Za-z]{3}\/2003/', $line)

Many thanks,
Peter

Posted: Wed Jun 18, 2003 9:42 am
by releasedj
Oops, your one is correct. Sorry.