0

I'm very new to both JSON and PHP but I'm building a game that needs a seperate database that keeps track of the doors that are locked and unlocked in a maze.

My JSON file looks like this:

{ "doors": 
    [
        {"left":true, "right":false, "bottom":false}, 
        {"left":false, "right":false, "bottom":false},
        {"right":false, "bottom":false, "top":false}
    ]
}

and my PHP file looks like this:

$jsonString = file_get_contents('info.json');
$data = json_decode($jsonString);
$data["doors"][0]["right"] = true;
$newJsonString = json_encode($data);
file_put_contents('info.json', $newJsonString);

I'm calling this using ajax in javascript and I can read the file if I use var_dump($data) but as soon as I try to edit the file I get a 500 error. I feel like I'm really close, but I'm just really stuck right now. If someone could help me out that would be really great. Thanks.

Josephine
  • 261
  • 2
  • 10
  • 20

2 Answers2

2

Are you running this in var/www through localhost or some other server folder? If so the web-process may not have sufficient privileges to write to the directory.

Edit: If you are running in a restricted directory (e.g. var/www or outside you user dir) you may try and change the permission of the file you are trying to write to with something like: (try this only cd'd into the dir where your JSON file is)

sudo chmod -777 info.json

(then enter your pw if you are a linux box) Please be aware, though, that is for testing purposes only and may lead to security & performance concerns: For more information about this particular level of security with file permissions please view: In a PHP / Apache / Linux context, why exactly is chmod 777 dangerous?

Community
  • 1
  • 1
Cristian Cavalli
  • 2,619
  • 1
  • 13
  • 11
1

A 500 error is an Internal Server Error. It usually means that there is a misconfiguration somewhere. The best way to debug it is by checking your web server's error log, it should tell you why it threw a 500 error.

Also, be aware that a json_decode() without the second $assoc parameter, returns an object rather than an array, so to overrule a key you'd need to set it as an object property:

$data->doors[0]->right = true;
Oldskool
  • 34,211
  • 7
  • 53
  • 66