note 86884 added to function.eval
| From: | maurice at chandoo dot de | Date: | Fri, 07 Nov 2008 23:20:02 +0000 |
| Subject: | note 86884 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-146300@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
@Mark dot Sheppard at disney dot com
How about replacing 'exit' with 'return 0'
----
Server IP: 217.160.72.57
Probable Submitter: 82.83.239.174
----
Manual Page -- http://www.php.net/manual/en/function.eval.php
Edit -- https://master.php.net/note/edit/86884
Del: integrated -- https://master.php.net/note/delete/86884/integrated
Del: useless -- https://master.php.net/note/delete/86884/useless
Del: bad code -- https://master.php.net/note/delete/86884/bad+code
Del: spam -- https://master.php.net/note/delete/86884/spam
Del: non-english -- https://master.php.net/note/delete/86884/non-english
Del: in docs -- https://master.php.net/note/delete/86884/in+docs
Del: other reasons-- https://master.php.net/note/delete/86884
Reject -- https://master.php.net/note/reject/86884
Search -- https://master.php.net/manage/user-notes.php