The script started off with some simple configuration…
<?php$file = 'data/data_tracker.txt';$maxlen = 300000; // bytes/chars before file truncation begins$input = '<p style="padding:0; line-height:130%;"><strong>'.'IP: '.getenv('REMOTE_ADDR'). "</strong><br />\n".' <span style="font-size:85%;">DT: '.date("M jS, Y - g:i a"). "<br />\n".' PG: '.getenv('REQUEST_URI'). "<br /></span></p>\n\n";?>- Download this code: tracker_1.txt
The settings are pretty clear: $file is the location of the tracking file to be written to, $maxlen is the maximum filesize (in bytes) that $file can reach, and $input is what will be prepended to the file. Let’s move on.
<?phpif(@$handle = fopen($file, 'r')){$data = @fread($handle, filesize($file));fclose($handle);}while(strlen($data) > $maxlen){$temp = explode("\n\n", $data);unset($temp[count($temp)-1]);$data = implode("\n\n", $temp);}if(@$handle = fopen($file, 'w')){fwrite($handle, $input.$data);fclose($handle);unset($file, $maxlen, $input, $data, $temp, $handle);}?>- Download this code: tracker_2.txt
The first thing we do is open and read the file. The contents of $file are loaded into the $data variable.
Next is the best part of the script. We run a while loop, checking the strlen() of the $data variable, and making sure that it is greater than the $maxlen. As long as it is, we can delete chunks of data at a time. We don’t want to remove each letter until it is at exactly $maxlen in bytes, but we want to remove the oldest chunks of data until the amount of bytes is less than or equal to $maxlen. Generally, the file size will be kept less than $maxlen, depending on the size of each chunk.
The last part just writes the new data, following truncation (if necessary), and prepends $input.
Anyway, I found this routine helpful and figured I’d share it with anyone who may be interested in accomplishing something similar. Download the entire code: tracker_3.txt.

You do know about ftruncate(), right?
Sorry if it doesn’t apply, I kind of just skimmed the rest of the entry.
December 13th, 2005 at 12:32 am
Dan, in this case, it doesn’t apply, since the file needs to be truncated in specific chunks. Thanks for pointing that out, though.
December 14th, 2005 at 2:49 pm