Many thanks, BitPoet. I wasn't even aware of that function. It may be a while before I see if it solves the problem, but for what it's worth, here is how I implemented locking in lazy cron and the script called from AJAX:
excerpt from lazy cron:
$json = json_encode($mapData);
$fp = fopen('site/templates/api.json', 'r+');
if (flock($fp, LOCK_EX)) { // lock the file
fwrite($fp, $json);
flock($fp, LOCK_UN); // unlock the file
//$log->save('user_activities','api.json updated with ' . count($mapData['locations']) . ' records');
} else {
// flock() returned false, no lock obtained
$log->save('user_activities',"Could not lock api.json. Update failed");
}
fclose($fp);
excerpt from form.php:
// lock api.json while reading/writing to prevent collision with lazycron
$handle = fopen('api.json', 'r');
while (!flock($handle, LOCK_SH)) { usleep(1); }
$inp = fread($handle, filesize('api.json'));
$tempArray = json_decode($inp, true); // convert json to php array
array_push($tempArray['locations'], $mapData['locations']); // add new data to end of array
$jsonData = json_encode($tempArray); // convert back to json
file_put_contents('api.json', $jsonData); // re-write the file
flock($handle, LOCK_UN);
fclose($handle);