flock - when to use?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
soonic
Forum Newbie
Posts: 9
Joined: Fri Jan 13, 2012 1:04 pm

flock - when to use?

Post by soonic »

Hi

I'm thinking when I should use just flock and when it isn't needed? (I'm also using flock with extra protection the code which I found at PHP man)
I've two cases when I call a files to write:

1) a visit counter.php calls a file to write visits
My website is: a.php, b.php, and so on.
Inside counter.php I use this function to check the file can write:

Code: Select all

function checkfLock($fname)
  {
    $startTime = microtime();
    do 
    {
      $canWrite = flock($fname, LOCK_EX);
      if(!$canWrite) usleep(round(rand(0, 100)*1000));
    } while ((!$canWrite)and((microtime()-$startTime) < 1000));
    return $canWrite;
  }

if ($save_file = fopen($fileon, 'w'))
  {
    $canWrite=checkfLock($save_file);
    if ($canWrite) 
    {
      fwrite($save_file, $save);
    }
    flock($save_file, LOCK_UN); 
    fclose($save_file); 
  }   
Is it really needed (the method above) in a case where only one script (counter.php) writes to txt file? But many users can call this script at once but wouldn't be enough just to use flock like this:

Code: Select all

flock($fname, LOCK_EX);
fwrite($fname, 'a');
flock($fname, LOCK_UN); 
without waiting function or even not use flock at all? Am I right that the method above should be used when I'd have use two or more scripts which try to write the same file?

2) The second case is that I have form which I write to a file, but this is similar to web counter (one php script but many users can call it at the same time but here I also use sessions for other purpose. I'm not sure how session work with flock). Please explain me the purpose of using flock according to my examples.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: flock - when to use?

Post by Weirdan »

the waiting part is not needed - flock blocks until it can acquire the lock (unless LOCK_NB is provided in the flags, but it's not in your case).

you need flock when there could be several instances of the script(s) writing to the same file (even if there's just one script file). Flock (with exclusive lock type) is used to make sure there's only one thread writing at any given time. Without flock you may get the data in the file all messed up.

If you use default file-based session handler the session files are automatically locked to ensure safe semi-concurrent access, you don't need to lock them manually.
Post Reply