Using PHP to maintain a specific filesize

The script started off with some simple configuration…

  1. <?php
  2. $file = 'data/data_tracker.txt';
  3. $maxlen = 300000; // bytes/chars before file truncation begins
  4. $input = '<p style="padding:0; line-height:130%;"><strong>'
  5. .'IP: '.getenv('REMOTE_ADDR'). "</strong><br />\n"
  6. .' <span style="font-size:85%;">DT: '.date("M jS, Y - g:i a"). "<br />\n"
  7. .' PG: '.getenv('REQUEST_URI'). "<br /></span></p>\n\n";
  8. ?>

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.

  1. <?php
  2.  
  3. if(@$handle = fopen($file, 'r')){
  4. $data = @fread($handle, filesize($file));
  5. fclose($handle);
  6. }
  7.  
  8. while(strlen($data) > $maxlen){
  9. $temp = explode("\n\n", $data);
  10. unset($temp[count($temp)-1]);
  11. $data = implode("\n\n", $temp);
  12. }
  13.  
  14. if(@$handle = fopen($file, 'w')){
  15. fwrite($handle, $input.$data);
  16. fclose($handle);
  17. unset($file, $maxlen, $input, $data, $temp, $handle);
  18. }
  19.  
  20. ?>

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.

Newsvine | Del.icio.us | Digg
In Web, PHP on December 11th, 2005 | 2 Remarks

2 Remarks to “Using PHP to maintain a specific filesize”

  1. Daniel remarks:

    You do know about ftruncate(), right?

    Sorry if it doesn’t apply, I kind of just skimmed the rest of the entry.

  2. Jona remarks:

    Dan, in this case, it doesn’t apply, since the file needs to be truncated in specific chunks. Thanks for pointing that out, though.

Leave a Remark

 

Note: HTML is allowed. (<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong> ).