PHP error while incrementing values in JSON file

My code so far :

<?PHP
header('Access-Control-Allow-Origin: *');

$src = $_POST["src"];

$jsonString = file_get_contents('jsonFile.json');
$data = json_decode($jsonString, true);

foreach ($data as $key => $entry) {
    if ($entry['src'] == $src) {
        $data[$key]['counter']++;
    }
}

$newJsonString = json_encode($data);
file_put_contents('jsonFile.json', $newJsonString);
?>

My json file looks like this:

[
        {
            "src": "",
            "counter": "0"
        },
        {
            "src": "",
            "counter": "0"
        } // and so on...

Expected behaviour is to increment the counter value of matching source supplied by POST by 1.

The error in logs is PHP Warning: Invalid argument supplied for foreach() in /file.php on line 9 .

When I do var_dump($data) I get output NULL.

Where do I go wrong ?

To do this properly, your code must -

  1. Detect if a post method form has been submitted before referencing any post data.
  2. Trim, then validate that the input is not empty and contains a permitted src value.
  3. Use file locking to insure that concurrent requests don’t cause the content of the file to be reset.
  4. Have error handling for every statement that can fail - file_get_contents, json_decode, and file_put_contents. For json_decode(), if it fails, json_last_error_msg() and json_last_error() will contain information about the error.
  5. Even if json_decode() succeeds without an error, it may not produce an array, depending on what the actual json input is. You must therefore test if $data is an array and is not empty before tying to loop over it.
  6. Your code should ‘automatically’ insert new records into the file for you, so that you don’t need to continually edit the file for every src value that gets added to an application.

The code for the file/data operations (items 3-6) already exists. It is called a database engine. You should be using a database for this. All it takes to accomplished these steps is a single INSERT … ON DUPLICTE KEY UPDATE … sql query.

try {
    $data = json_decode(file_get_contents('jsonFile.json'), true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
}

I don’t know if it will work, but I think it might? Phdr made really good points.

post function in js:

        var srcd = document.getElementById("pictwo").src;

        $.ajax({
          type: "POST", //type of method
          url: "/file.php", //your page
          data: {
            src: srcd
          }, // passing the values
          success: function(res) {
            location.reload(); //do what you want here...

          }

        });
      }

file.php:

<?php
header('Access-Control-Allow-Origin: *');

$src = $_POST["src"];
$jsonString = file_get_contents('jsonFile.json');
$data = json_decode( $jsonString, true );

foreach ( $data as $key => $entry )
{
        if ( $entry['src'] == $src )
        {
                $data[$key]['counter']++;
        }
}
$newJsonString = json_encode( $data );
file_put_contents( 'jsonFile.json', $newJsonString );

?>

I know that the POST is successful, because I added a console.log(srcd) to the js function, and it was the desired value.

jaonFile.json:

[
        {
            "src": "https://",
            "counter": "0"
        },
        {
            "src": "https://",
            "counter": "0"
        },
        {
            "src": "https://",
            "counter": "0"
        },

The error in error_logs is :

PHP Warning: Invalid argument supplied for foreach() in /file.php on line 8

After the function is called, the json file is changed to null.

Why is this happening?

How can I fix this?

Thank you.

@kyrgios, I have merged your two topics.

Please read the detailed reply you already have received concerning the code you need to successfully do this.

The reason for nulling out the jason file is because you don’t have any error handling and your code is blindly putting the null result into the file. Code with error handling would only put the data back into the file when there are no errors.

Sponsor our Newsletter | Privacy Policy | Terms of Service