note 86884 modified in function.eval by danbrown

From: Date: Sun, 17 May 2009 19:51:25 +0000
Subject: note 86884 modified in function.eval by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-155280@lists.php.net to get a copy of this message
<?php function safe_eval($code,&$status) { //status 0=failed,1=all clear //Signs //Can't assign stuff $bl_signs = array("="); //Language constructs $bl_constructs = array("print","echo","require","include","if","else", "while","for","switch","exit","break"); //Functions $funcs = get_defined_functions(); $funcs = array_merge($funcs['internal'],$funcs['user']); //Functions allowed //Math cant be evil, can it? $whitelist = array("pow","exp","abs","sin","cos","tan"); //Remove whitelist elements foreach($whitelist as $f) { unset($funcs[array_search($f,$funcs)]); } //Append '(' to prevent confusion (e.g. array() and array_fill()) foreach($funcs as $key => $val) { $funcs[$key] = $val."("; } $blacklist = array_merge($bl_signs,$bl_constructs,$funcs); //Check $status=1; foreach($blacklist as $nono) { if(strpos($code,$nono) !== false) { $status = 0; return 0; } } //Eval return @eval($code); } ?> Note: Try to include this after all of your other self-defined functions and consider whether the blacklist is appropriate for your purpose I wouldn't recommend this function if you're going to use eval extensively in your script. However, it's worth a try if you are going to put user input into eval --was-- <?php function safe_eval($code,&$status) { //status 0=failed,1=all clear //Signs //Can't assign stuff $bl_signs = array("="); //Language constructs $bl_constructs = array("print","echo","require","include","if","else", "while","for","switch","exit","break"); //Functions $funcs = get_defined_functions(); $funcs = array_merge($funcs['internal'],$funcs['user']); //Functions allowed //Math cant be evil, can it? $whitelist = array("pow","exp","abs","sin","cos","tan"); //Remove whitelist elements foreach($whitelist as $f) { unset($funcs[array_search($f,$funcs)]); } //Append '(' to prevent confusion (e.g. array() and array_fill()) foreach($funcs as $key => $val) { $funcs[$key] = $val."("; } $blacklist = array_merge($bl_signs,$bl_constructs,$funcs); //Check $status=1; foreach($blacklist as $nono) { if(strpos($code,$nono) !== false) { $status = 0; return 0; } } //Eval return @eval($code); } ?> Note: Try to include this after all of your other self-defined functions and consider whether the blacklist is appropriate for your purpose I wouldn't recommend this function if you're going to use eval extensively in your script. However, it's worth a try if you are going to put user input into eval @Mark dot Sheppard at disney dot com How about replacing 'exit' with 'return 0' http://php.net/manual/en/function.eval.php

« previous php.notes (#155280) next »