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); } }Si los intervalos entre las transferencias de datos son muy cortos, los datos se pierden. ¿Cómo prevenir esto?
Esto suena como una condición de carrera, probablemente porque varias solicitudes escriben en el mismo archivo data.json al mismo tiempo.
Debería poder evitar esto bloqueando el archivo para que solo un proceso PHP tenga acceso a él a la vez.
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!"; } } }