Cyclone
Cyclone

Reputation: 18295

file_put_contents wipes the file

If two people load the same page within approximately 5 milliseconds of each other, the two simultaneous file_put_contents calls seem to wipe the file blank, losing all data.

How can I write to files securely in such a manner that the file will never be wiped blank, no matter how many people load the page at the exact same time?

I cannot use a mysql database for this, that'd be extremely excessive.

Upvotes: 1

Views: 553

Answers (3)

Geri Borbás
Geri Borbás

Reputation: 16598

/**
 * Writes a file without the worry on simultaneous file writings.
 *
 * @param mixed $data - Data to put into the file.
 * @param string $filePath - Path to the file to put data into.
 * @param number $timeOut - The maximum time (milliseconds) until method attempts to write file (defaults to 1000).
 * @return bool - Returns true if data has been written.
 */
function writeDataToFileSafely($data, $filePath, $timeOut = 1000)
{
    $interval = 10; // milliseconds
    $elapsed = 0;
    $success = false;

    while($success === false && $elapsed < $timeout)
    {
        $success = file_put_contents($filePath, $data, LOCK_EX);
        usleep(interval * 1000); // to microseconds
        $elapsed += $interval;
    }

    return $success;
}

Upvotes: 0

mrkmg
mrkmg

Reputation: 241

In your php use a while loop and check for a file lock.

Here is some reading http://php.net/manual/en/function.flock.php

EDIT

$fp = fopen("/tmp/lock.txt", "r+");
while(!flock($fp, LOCK_EX))
      {
      usleep(10);
      }
//do stuff
flock($fp, LOCK_UN);
fclose($fp);

Upvotes: 1

user680786
user680786

Reputation:

file_put_contents has third parameter. Write LOCK_EX there.

Upvotes: 4

Related Questions