text file behavior

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Karl Hungus

    text file behavior


    I have a question about the behavior of a text file thats being written and
    read to.

    Say Im using an XML file as the database for my little application. Users
    come to my site and the file is read and parsed and coverted to some display
    in html. On another page users can add information that updates this XML
    file.

    Is there any risk in this approach? While the XML file is being written to,
    what is its readabililty? And vise-versa. Assuming Im using the standard
    read write functions for files in PHP, will the read wait for a write to
    finish, etc.

    Thanks in advance


  • Pedro Graca

    #2
    Re: text file behavior

    Karl Hungus wrote:[color=blue]
    > I have a question about the behavior of a text file thats being written and
    > read to.[/color]
    (snip)[color=blue]
    > Is there any risk in this approach? While the XML file is being written to,
    > what is its readabililty? And vise-versa. Assuming Im using the standard
    > read write functions for files in PHP, will the read wait for a write to
    > finish, etc.[/color]

    I think you should use the file-locking mechanism to avoid risk.



    <?php
    $xml = '/path/to/xmlfile.xml';
    $f = fopen($xml, 'w') or die('cannot open file ' . $xml);

    // try $n times to lock the file
    // waiting 1 milli-second between each attempt
    $n = 6;
    while ($n) {
    if (flock($f, LOCK_EX)) break;
    --$n;
    usleep(1000);
    }
    if ($n == 0) die('Could not lock the file' . $xml)

    // write data
    fwrite($f, 'whatever');

    // unlock and close the file
    flock($f, LOCK_UN);
    fclose($f);
    ?>
    --
    --= my mail box only accepts =--
    --= Content-Type: text/plain =--
    --= Size below 10001 bytes =--

    Comment

    Working...