Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
¿Cómo garantizar que no se pierdan datos al transferirlos y almacenarlos en el servidor?

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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!"; } } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!