PHP\'s documentation page for flock() indicates that it\'s not safe to use under IIS. If I can\'t rely on flock under all circumstances, is there another way I
Based on mkdir:
// call this always before reading or writing to your filepath in concurrent situations
function lockFile($filepath){
clearstatcache();
$lockname=$filepath.".lock";
// if the lock already exists, get its age:
$life=@filectime($lockname);
// attempt to lock, this is the really important atomic action:
while (!@mkdir($lockname)){
if ($life)
if ((time()-$life)>120){
//release old locks
rmdir($lockname);
}else $life=@filectime($lockname);
usleep(rand(50000,200000));//wait random time before trying again
}
}
To avoid deadlock when one script in case a script exits before it has unlocked and one (or more scripts) at the same time have no result on $life=@filectime($lockname); because all scripts starts at the same time and then directory isn't created yet. To unlock then call:
function unlockFile($filepath){
$unlockname= $filepath.".lock";
return @rmdir($unlockname);
}