JavaScript:
const XHR = new XMLHttpRequest();
function sendData(data) {
XHR.open('POST', 'savedata.php');
XHR.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
XHR.send('data=' + JSON.stringify(data);
}
PHP:
if (isset($_POST['data'])) {
if (file_exists('data.json')) {
$file = file_get_contents('data.json');
$accumulatedData = json_decode($file);
$data = json_decode($_POST['data']);
array_push($accumulatedData, $data);
$encodedAccumulatedData = json_encode($accumulatedData);
file_put_contents('data.json', $encodedAccumulatedData);
}
}
If the intervals between the data transfers are very short, data get lost. How to prevent this?
This sounds like a race condition, likely because multiple requests write to the same data.json file at the same time.
You should be able to prevent this by locking the file so only one PHP process has access to it at a time.
if (isset($_POST['data'])) {
if (file_exists('data.json')) {
$fp = fopen("data.json", "r+");
// acquire an exclusive lock, block until we can aquire it.
if (flock($fp, LOCK_EX)) {
// we can still use file_get_contents, which is better than using fread.
$file = file_get_contents('data.json');
$accumulatedData = json_decode($file);
$data = json_decode($_POST['data']);
array_push($accumulatedData, $data);
$encodedAccumulatedData = json_encode($accumulatedData);
// Remove existing file contents
ftruncate($fp, 0);
// Write new JSON array to file
fwrite($fp, $encodedAccumulatedData);
// release the lock
flock($fp, LOCK_UN);
} else {
// This should rarely happen since flock will block until it can get a lock.
// just in case, we should instruct the client to try again later.
echo "Couldn't get the lock!";
}
}
}