Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Whilst writing a parser using the Tokenizer which turned out not as easy as I expected, I came up with another idea: Why not parse the array using <code>eval</code>, but first validate that it contains nothing harmful?</p> <p>So, what the code does: It checks the tokens of the array against some allowed tokens and chars and then executes eval. I do hope I included all possible harmless tokens, if not, simply add them. (I intentionally didn't include HEREDOC and NOWDOC, because I think they are unlikely to be used.)</p> <pre><code>function parseArray($code) { $allowedTokens = array( T_ARRAY =&gt; true, T_CONSTANT_ENCAPSED_STRING =&gt; true, T_LNUMBER =&gt; true, T_DNUMBER =&gt; true, T_DOUBLE_ARROW =&gt; true, T_WHITESPACE =&gt; true, ); $allowedChars = array( '(' =&gt; true, ')' =&gt; true, ',' =&gt; true, ); $tokens = token_get_all('&lt;?php '.$code); array_shift($tokens); // remove opening php tag foreach ($tokens as $token) { // char token if (is_string($token)) { if (!isset($allowedChars[$token])) { throw new Exception('Disallowed token \''.$token.'\' encountered.'); } continue; } // array token // true, false and null are okay, too if ($token[0] == T_STRING &amp;&amp; ($token[1] == 'true' || $token[1] == 'false' || $token[1] == 'null')) { continue; } if (!isset($allowedTokens[$token[0]])) { throw new Exception('Disallowed token \''.token_name($token[0]).'\' encountered.'); } } // fetch error messages ob_start(); if (false === eval('$returnArray = '.$code.';')) { throw new Exception('Array couldn\'t be eval()\'d: '.ob_get_clean()); } else { ob_end_clean(); return $returnArray; } } var_dump(parseArray('array("a", "b", "c", array("1", "2", array("A", "B")), array("3", "4"), "d")')); </code></pre> <p>I think this is a good comprimise between security and convenience - no need to parse yourself.</p> <p>For example</p> <pre><code>parseArray('exec("haha -i -thought -i -was -smart")'); </code></pre> <p>would throw exception:</p> <pre><code>Disallowed token 'T_STRING' encountered. </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload