Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

204
Vistas
How to ensure that no data get lost while transferring them to and storing them on the server?

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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!";
        }
    }
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda