note 97681 deleted from function.eval by danbrown
| From: | danbrown@php.net | Date: | Sun, 02 May 2010 22:35:24 +0000 |
| Subject: | note 97681 deleted from function.eval by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-168866@lists.php.net to get a copy of this message | ||
Note Submitter: thierrycatrain at gmail dot com
----
This is a secure matheval that can handle maths functions as well. Complements cmr at expansys dot
com matheval.
<?php
function matheval($string) {
$function = array( "abs",
"acos",
"acosh",
"asin",
"asinh",
"atan2",
"atan",
"atanh",
"base_convert",
"bindec",
"ceil",
"cos",
"cosh",
"decbin",
"dechex",
"decoct",
"deg2rad",
"exp",
"expm1",
"floor",
"fmod",
"getrandmax",
"hexdec",
"hypot",
"is_finite",
"is_infinite",
"is_nan",
"lcg_value",
"log10",
"log1p",
"log",
"max",
"min",
"mt_getrandmax",
"mt_rand",
"mt_srand",
"octdec",
"pi",
"pow",
"rad2deg",
"rand",
"round",
"sin",
"sinh",
"sqrt",
"srand",
"tan",
"tanh",
);
$chars = array( '0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
' ',
'(',
')',
'/',
'*',
'-',
'+',
);
for ($i = 0; $i < strlen($string); $i++) {
if (in_array($string[$i], $chars))
continue;
$fct = $string[$i];
while (in_array_partial(($fct . $string[$i + 1]), $function))
$fct .= $string[++$i];
if (!in_array($fct, $function))
return ("SECURITY ERROR");
}
return (eval("echo " . $string . ";"));
}
function in_array_partial($string, Array $array) {
foreach ($array as $value)
if (!strncmp($string, $value, strlen($string)))
return (true);
return (false);
}
?>