Antoine089
Antoine089

Reputation: 458

Overwriting Json File with new Json Data

So I have this json file (json.json) stored on a server, I would like to overwrite it with new json Data ('refresh_token' object to be exact) everytime I call on this php class:

    $file = file_get_contents('/var/json.json');
    $json = json_decode($file);
    **$REFRESH_TOKEN** = $json->refresh_token;

    $json = file_get_contents("https://xxxxxxxxxxx&refresh_token=**$REFRESH_TOKEN**");
    $obj = json_decode($json, true);
    $AccessToken = $obj->access_token;
    $RefreshToken = $obj->refresh_token;
    **file_put_contents('/var/json.json', json_encode($RefreshToken));**

The json file looks like this:

     {"token_type":"bearer",
    "expires_in":3600,
    "scope":"xxxxxxx",
    "access_token":"xxxx",
    **"refresh_token":"xxxxx",**
    "user_id":"xxxxxx"}

I repeatedly get the error: Trying to get property of non-object in whenever I call the class for a second time. I looked inside the json file after the first call and realized that it did not contain anything. This indicates that the file_put_contents('/var/json.json', json_encode($RefreshToken)) did not work.

Can anyone give me a hint as to what i'm doing wrong here?

Upvotes: 1

Views: 1981

Answers (3)

Mihai Scurtu
Mihai Scurtu

Reputation: 1478

If you set the 2nd parameter of json_decode to true you get an associative array instead of an object.

Documentation for json_decode: http://php.net//manual/en/function.json-decode.php

Upvotes: 0

Alexander
Alexander

Reputation: 20234

From your code, it is not obvious what you are trying to do. I guess it is the following:

  • fetch json object from file
  • modify refresh token
  • write json object back to file

This would work as follows:

$REFRESHTOKEN = $_GET['REFRESH_TOKEN']; // Calculate refresh token
$json = json_decode(file_get_contents('/var/json.json')); // fetch json object from file
$json->refresh_token = $REFRESHTOKEN // modify refresh token
file_put_contents('/var/json.json', json_encode($json)); // write json object back to file

What you are doing is writing ONLY the refresh token into the file, not the whole object. This is why on the second attempt, the object is not there...

Upvotes: 0

skywards
skywards

Reputation: 89

Make sure you have permission to write on the file. Change file permission to 777.

Upvotes: 1

Related Questions