how to write concurrent data in json file in php

<?php
$file = 'data.json';
$fp = fopen($file, 'c+'); // Open for reading and writing, create if not exists

if (flock($fp, LOCK_EX)) { // Acquire an exclusive lock
    $current_data = [];
    if (filesize($file) > 0) {
        $json_content = fread($fp, filesize($file));
        $current_data = json_decode($json_content, true);
        if ($current_data === null) {
            // Handle JSON decoding error
            error_log("Error decoding JSON from $file. Resetting data.");
            $current_data = [];
        }
    }

    // Simulate adding new data
    $new_entry = [
        'id' => uniqid(),
        'message' => 'Hello from process ' . getmypid(),
        'timestamp' => date('Y-m-d H:i:s')
    ];

    $current_data[] = $new_entry;

    ftruncate($fp, 0); // Truncate the file
    rewind($fp);      // Rewind file pointer

    $json_output = json_encode($current_data, JSON_PRETTY_PRINT);
    fwrite($fp, $json_output);

    flock($fp, LOCK_UN); // Release the lock
    fclose($fp);
    echo "Data written successfully by process " . getmypid() . "\n";
} else {
    echo "Could not acquire lock for $file by process " . getmypid() . "\n";
}
?>
 $file = 'activitydata.json';
    $fp = fopen($file, 'c+');   

if (flock($fp, LOCK_EX)) {
    $arrayData = [];
     if (filesize($file) > 0) {

        $currentData =  fread($fp, filesize($file));
        $arrayData = json_decode($currentData, true);  // true for associative array
            if ($arrayData === null) {
            // Handle JSON decoding error
            error_log("Error decoding JSON from $file. Resetting data.");
            $arrayData = [];
        }
     }
       $arrayData[] = $success;
       ftruncate($fp, 0); // Truncate the file
       rewind($fp);      // Rewind file pointer
         $jsonData = json_encode($arrayData, JSON_PRETTY_PRINT); // JSON_PRETTY_PRINT for readability
         fwrite($fp, $jsonData);
         flock($fp, LOCK_UN); // Release the lock
         fclose($fp);
}



Leave a Reply