Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP and concurrent file access

I'm building a small web app in PHP that stores some information in a plain text file. However, this text file is used/modified by all users of my app at some given point in time and possible at the same time.

So the questions is. What would be the best way to make sure that only one user can make changes to the file at any given point in time?

like image 577
Luke Avatar asked Nov 16 '08 06:11

Luke


1 Answers

You should put a lock on the file

    $fp = fopen("/tmp/lock.txt", "r+");

if (flock($fp, LOCK_EX)) {  // acquire an exclusive lock
    ftruncate($fp, 0);      // truncate file
    fwrite($fp, "Write something here\n");
    fflush($fp);            // flush output before releasing the lock
    flock($fp, LOCK_UN);    // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);

Take a look at the http://www.php.net/flock

like image 147
andy.gurin Avatar answered Oct 04 '22 07:10

andy.gurin