title: How to safely write JSON data to file using PHP
body: <p>I've got HTML form for editing images. All data is stored in JSON. When I change current image, I want to save changes, through PHP script, to a text file. If I return to previous image, this configuration will be send again from this file to the form.</p>
  
  <p>My question is:</p>
  
  <p><strong>How to write/read this kind of data safely. Where and how effectively check data to prevent some JS/PHP code injections?</strong></p>
  
  <p>I have attached some concept code below:</p>
  
  <p>JavaScript (using jQuery):</p>
  
  <pre><code>// Writing
  $.ajax({
      global: false,
      type: "POST",
      cache: false,
      dataType: "json",
      data: ({
          action: 'write',
          config: JavaScriptJSON_Obj
      }),
      url: 'read-write.php'
  });
  
  // Reading
  $.ajax({
      global: false,
      type: "POST",
      cache: false,
      dataType: "json",
      data: ({
          action: 'read'
      }),
      url: 'read-write.php',
      success: function(data){
          JavaScriptJSON_Obj = data;
      }
  });
  </code></pre>
  
  <p>PHP example (read-write.php):</p>
  
  <pre><code>switch ($_REQUEST['action']) {
      case 'write':
          file_put_contents('config.txt', $_REQUEST['config']);
          break;
      case 'read':
          $s = file_get_contents('config.txt');
          echo json_encode($s);
          break;
  }
  </code></pre>