1

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.

6
  • Why would using a database to handle such concurrency be excessive?
    – Brad
    May 25, 2011 at 21:02
  • @Brad Because it's one single file holding a small amount of data.
    – Cyclone
    May 25, 2011 at 21:03
  • will have to guess what your code has here. Are you using File append? and are you using flock() to lock the file if it has been accessed?
    – Duniyadnd
    May 25, 2011 at 21:04
  • @Duniyadnd Read the question title, body, and tags more closely.
    – Cyclone
    May 25, 2011 at 21:05
  • 1
    Use a unique filename instead of a fixed one?
    – Marc B
    May 25, 2011 at 21:25

3 Answers 3

4

file_put_contents has third parameter. Write LOCK_EX there.

4
  • I wasn't aware of this flag, thanks for sharing the info. I've implemented it already as a safe-guard in some libraries I've written.
    – Mog
    May 25, 2011 at 21:13
  • Is the LOCK_EX flag blocking? It should be, otherwise...kinda pointless
    – Cyclone
    May 25, 2011 at 21:14
  • @Wesley Murch, glad to useful )
    – OZ_
    May 25, 2011 at 21:15
  • 1
    @Cyclone, did you read manual? Acquire an exclusive lock on the file while proceeding to the writing.
    – OZ_
    May 25, 2011 at 21:16
1

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);
1
  • So until it receives the lock, it won't be able to write to the file?
    – Cyclone
    May 25, 2011 at 21:04
0
/**
 * 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;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.