title: Is it safe to call json_decode on user input?
body: <p>I'm storing a JSON encoded array of integer indexes =&gt; integer values in a cookie.</p>
  <p>Obviously cookies can be easily manipulated like any other user input, so here's my cookie getter validation:</p>
  <pre><code>if ($_COOKIE['myCookie']) { //if cookie exists
      $myCookie = json_decode($_COOKIE['myCookie'], true);
      if (!is_array($myCookie)) { //in case decoding fails or bad cookie
          $myCookie = array(); //sets it as empty array
      }
  } else { //if cookie doesn't exist, uses an empty array instead
      $myCookie = array();
  }
  </code></pre>
  <p>Then before using any of the values, I check if it exists in the array and test against a list of white-listed values - this part seems pretty safe but I'm posting it as it's part of the validation:</p>
  <pre><code>if (!empty($myCookie[$index])) { //checks if index exists and is truthy
      if ($myCookie[$index] !== 1 &amp;&amp; $myCookie[$index] !== 2) { //values whitelist
          die('Hacking attempt through cookies exploit.');
      }
      //use the cookie data now
  }
  </code></pre>
  <p>Back to the question, <strong>is it safe  to call <code>json_decode</code> directly on the cookie?</strong> Can users manipulate the cookie to run arbitrary code?</p>
  <p>I've been reading around many topics on SO so far and what I found is that <code>unserialize()</code> is dimmed unsafe because it calls constructors, but <code>json_decode</code> is technically safe. I've read through their php.net pages but those do not address security directly.</p>
  <p>My addon is reaching the live beta very soon, so I'm wondering if calling <code>json_decode</code> directly on the cookie is safe enough or if I should run some type of validation before calling <code>json_decode</code>. I could run a <code>preg_match</code> too, but as I'm testing against a whitelist of values before using them, there should be no problem unless <code>json_decode</code> somehow runs arbitrary code, which it doesn't, right?</p>
  <p>I know that <code>json_encode</code> returns <code>NULL</code> if it's not valid JSON, but I'm wondering if this is the right approach or <strong>should I add some kind of validation before calling <code>json_decode</code>?</strong></p>