PHP save array for different instances of a script

Viewed 74

My PHP script are triggered via POST from different sources. There is a array, where elements are added and deleted.

I save this array with

$jsonString = json_encode($curList);
file_put_contents("curList.obj", $jsonString); 

and read it with

$stringified1 = file_get_contents("curList.obj") ?: '';
$curList = json_decode($stringified1, true) ?: [];

This works usually fine. But now I got in trouble, because several instances are running at the same time and read and write the array in the same time period. This creates problems, because some information are going lost.

It is possible to make sure, that another instance has to be wait, until the read and update of the file is finished?

Or is it possible that only one instance of the script is running at the same time, without a POST get lost?

2 Answers

Thanks to @Maksim I found the following solution:

        $file = "curList.obj";
        $lock = "curList.lock";
        while(true){
            if(!file_exists($lock)){
                $fHandle = fopen($lock, 'x');
                if($fHandle != false)
                    break;
            } 
            usleep(20);
        }
        $stringified1 = file_get_contents("curList.obj") ?: '';
        $curList = json_decode($stringified1, true) ?: [];
        $curList[] = $_POST;
    // save array
        $jsonString = json_encode($curList);
        file_put_contents("curList.obj", $jsonString); 
    // release lock handle and delete lock
        fclose($fHandle);
        unlink($lock);

Why this solution.

I am using IIS 10 and there is a problem with IIS and flock. Therefore I build a kind of wrapper around the read and write of the data update. It is an additional curList.lock file.

First I check if the file exists, if not I create it with fopen($lock, 'x'). The option 'x' only creates the file if it not already exists. Otherwise it will fail and the routine is stil in the while loop, until it get an access.

try use Session in your project. With Sessions you can temporary save different data without conflicts. This information storage is unique to the user, but is not stored forever

Related