note 108552 deleted from function.json-decode by googleguy

From: Date: Fri, 30 Nov 2012 05:47:02 +0000
Subject: note 108552 deleted from function.json-decode by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-192223@lists.php.net to get a copy of this message
Note Submitter: Anonymous ---- <?php include_once('json_decode.php'); // #100740 's json_decode() var_dump(json_decode('"$json"')); var_dump(json_decode('"$omething"')); var_dump(json_decode('date("c")')); ?> In this code, a php without built-in json_decode() prints: string(7) ""$json"" string(0) "" string(25) "2012-05-05T00:00:00+00:00" expecting: string(5) "$json" string(9) "$omething" NULL They can be too vulnerable. To avoid them, it should be like below. Since this code is still not perfect, when you have to decode a JSON that might be invalid, you had better use a JSON library like PEAR or Zend's, or upgrade your php. <?php if (!function_exists('json_decode')) { function json_decode($json) { $comment = false; $out = '$x='; for ($i=0; $i<strlen($json); $i++) { if (!$comment) { if (($json[$i] == '{') || ($json[$i] == '[')) { $out .= 'array('; } elseif (($json[$i] == '}') || ($json[$i] == ']')) { $out .= ')'; } elseif ($json[$i] == ':') { $out .= '=>'; } elseif ($json[$i] == ',') { $out .= ','; } elseif ($json[$i] == '"') { $out .= '"'; } /*elseif (!preg_match('/\s/', $json[$i])) { return null; }*/ } else $out .= $json[$i] == '$' ? '\$' : $json[$i]; if ($json[$i] == '"' && $json[($i-1)] != '\\') $comment = !$comment; } eval($out. ';'); return $x; } } ?>

« previous php.notes (#192223) next »