PHP: Safe Eval
Want to allow your users to enter and parse PHP code, but don’t want them to blow up your server? Try this:
// parse potentially eval'able code for illegal function calls
function bd_parse($str) {
// allowed functions:
$allowedCalls = explode(
',',
'explode,implode,date,time,round,trunc,rand,ceil,floor,srand,'.
'strtolower,strtoupper,substr,stristr,strpos,print,print_r'
);
// check if there are any illegal calls
$parseErrors = array();
$tokens = token_get_all($str);
$vcall = '';
foreach($tokens as $token) {
if(is_array($token)) {
$id = $token[0];
switch ($id) {
case(T_VARIABLE): { $vcall .= 'v'; break; }
case(T_CONSTANT_ENCAPSED_STRING): { $vcall .= 'e'; break; }
case(T_STRING): { $vcall .= 's'; }
case(T_REQUIRE_ONCE): case(T_REQUIRE): case(T_NEW): case(T_RETURN):
case(T_BREAK): case(T_CATCH): case(T_CLONE): case(T_EXIT):
case(T_PRINT): case(T_GLOBAL): case(T_ECHO): case(T_INCLUDE_ONCE):
case(T_INCLUDE): case(T_EVAL): case(T_FUNCTION): case(T_GOTO):
case(T_USE): case(T_DIR): {
if (array_search($token[1], $allowedCalls) === false)
$parseErrors[] = 'illegal call: '.$token[1];
}
}
}
else $vcall .= $token;
}
// check for dynamic functions
if(stristr($vcall, 'v(')!='') $parseErrors[] = array('illegal dynamic function call');
return $parseErrors;
}
Check for safe code by running: if(count(bd_parse($user_code))==0)
Found and modified from the PHP.net website comments, it’s definitely not an exhaustive list or foolproof, but a good start against code injection attacks. Hope it helps someone.
Loading...
