faqts : Computers : Programming : Languages : PHP : Common Problems : Files

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 5 people (100%) answered Yes
Recently 4 of 4 people (100%) answered Yes

Entry

I want to restrict file sizes of the text files that I am using to store data. How do I write every 100th entry to a new file?

Feb 3rd, 2002 03:26
Philip Olson, mike gifford,


Your question is actually two, so we'll cover both :)  First, assuming
the restriction is based on filesize, use the PHP filesize() function:

  $size = filesize($filename);

Based on that size, either create a new file or append to the existing one.

  if (filesize($filename) < 20000) {
    
    $fp = fopen($filename, 'a');

  } else {

    $filename = time() . '.txt';

    $fp = fopen($filename, 'w');
  }

In the above, we'll create a new file based on the unix timestamp. 
There are other considerations but the above is a good start.

Now, regarding "limiting the number of entries" in a file.  Assuming
each entry is a line of the file, we can count newlines.  For example:

  $number_of_lines = sizeof(file($filename));

A "more" efficient way to count lines in a file, in linux, is through
the following command:

  wc -l

More on such counts can be read about in the following faqt:

  http://www.faqts.com/knowledge_base/view.phtml/aid/10147