A better PHP eval()
Tweet
Why not use PHP eval() directly?
Google 'php secure eval()' and you'll get the answer… :-D
For that reason, I created my own version of eval(): mv_eval(). It strips text, spaces, quotes and semicolons, and only the passes it to eval().
Here it is:
<?php
/*
Author : M.H.E. Vos
Copyright : (c) 2021, SDS82
Creation date : 2021-06-16
*/
function mv_eval($p1, $p2, $p3) {
/*
Use this function instead of eval() directly, to prevent PHP and SQL injection.
p1 = formula for eval(). Must be in ().
p2 = array() with texts and values to look for and replace in the formula
array('myvar' => $myvar[, ...])
or
array('$myvar' => $myvar[, ...])
Do not put the keys of the array between double quotes.
p3 = default value to return in case of errors. Can also be 'false'
Examples:
$zzVAR1 = mv_eval($varwithformula, array('myvar' => $myvar), false);
if($zzVAR1 === false) { print('Error in formula'); }
$zzVAR1 = mv_eval($varwithformula, array('myvar' => $myvar), 123);
*/
if(strlen($p1) < 3) {
return(false);
}
if(!is_array($p2)) {
return(false);
}
// Look for variables in formula
$f = $p1;
foreach($p2 as $key => $value) {
$f = str_replace(($key[0] != '$' ? '$' : '') . $key, $value, $f);
}
// After all variables have been replaced with their real vaules, remove remaining characters, single and double quotes and semicolons.
$f = preg_replace("/[a-zA-Z'\";]/", "", $f);
// Remove possible leftovers: spaces and empty round brackets, for example () or ( ()).
// A PHP formula does not need spaces.
$x = $f;
$f = str_replace('()', '', str_replace(' ', '', $f));
while($x != $f) {
$x = $f;
$f = str_replace('()', '', str_replace(' ', '', $f));
}
// Execute eval(). If it fails, return the default value.
try {
$x = @eval('return(' . $f . ');');
} catch (ParseError $e) {
$x = $p3;
}
return($x);
}
?>
That's it! Happy coding!