George Reith
George Reith

Reputation: 13476

PHP writing to file without truncation

I am creating a flatfile database, and I am trying to solve the problem of multiple edits being made at the same time. I understand I need to truncate the file for editing and deleting rows but for adding rows this is not necessary.

So if I were to use fopen($file, 'a') to write to a file, and multiple people where to open the file and write to it, would they all be able to write to the file simultaneously?

Without truncating the file people shouldn't be overwriting each other right?

Upvotes: 2

Views: 1566

Answers (1)

Marek Sebera
Marek Sebera

Reputation: 40621

It's better to use some kind of helper for this.

PHP function flock (File LOCK)

//Open the File Stream
$handle = fopen($file,"a");

//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
    $data;
    // do anything to fill variable $data
    fwrite($handle, $data);    //Write the $data into file
    flock($handle, LOCK_UN);    //Unlock File
} else {
    echo "Could not Lock File!";
}

//Close Stream
fclose($handle);

PHP file write threading issues
Read and write to a file while keeping lock

Upvotes: 2

Related Questions