Life after Guest
Life after Guest

Reputation: 327

PHP failing to write the same file multiple times if file is located in a subdirectory

I have three functions, basically doing the same thing (I know I can easily convert them to one function, but at the moment they must stay three).

The functions are similar to this one:

function setFlag($user_id, $flag)
{
    $file = $user_id . '_general_info.json';
    $recoveredData = file_get_contents($file);
    $recoveredArray = json_decode($recoveredData, true);
    $recoveredArray['isActive'] = $flag;
    $serializedData = json_encode($recoveredArray);
    file_put_contents($file, $serializedData, LOCK_EX);
}

so, they open the SAME file, get/decode its contents (JSON), add/update one of the JSON keys, save the file again.

The only difference between the functions is the JSON key they add or update.

Sometimes I have to call the functions one after another: anything works absolutely fine.

But if, in the first line of the function, I change the file path to a subdirectory, this way:

__DIR__ ."/". $user_id ."/". $user_id."_general_info.json"

for some reason only the latest key is added or updated into the file. So, for example, if I call:

A();
B();
C();

it is like I only called C(). If I comment out C(), the file doesn't write the key saved by A and writes the key B saves instead.

I suppose (even if at the moment I'm not sure) this has something to do with the fact that the code opens the same file multiple times.

But why in the current directory anything works fine and inside a subdirectory it fails?

Any help is appreciated.

Upvotes: 2

Views: 59

Answers (1)

oguzhancerit
oguzhancerit

Reputation: 1572

In your sample;

  1. A() function opens and locked the file
  2. B() function opens and locked the file
  3. C() function opens and locked the file

Locked file by C() function, only unlock by the C() function. While C() function updates the file, A() and B() function throws a warning. If your environment status is production, you can not see the warning. You can check here to change environment in development process.

Please take a look your error_log file and add some conditions to your code like if the file is locked or not.

Upvotes: 1

Related Questions