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.