flock - when to use?
Posted: Sat Feb 25, 2012 5:16 am
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:
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:
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.
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);
} Code: Select all
flock($fname, LOCK_EX);
fwrite($fname, 'a');
flock($fname, LOCK_UN);
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.