Re: Evaluating math without eval()

From: Date: Thu, 10 Apr 2008 16:58:20 +0000
Subject: Re: Evaluating math without eval()
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-272841@lists.php.net to get a copy of this message
Jason Norwood-Young wrote:
On Thu, 2008-04-10 at 13:15 +0100, Richard Heyes wrote:
First post to this list! I'm trying to figure out how to evaluate a string with a mathematical expression and get a result, but without using eval() as I'm accepting user input into the string. I don't just want addition, subtraction, multiplication and division - I'd like to take advantage of other functions like ceil, floor etc. So the string "18-10" should give me 8, "ceil(1/2)*10" should be 10 (if my maths is correct) and the string "18-10;\r\nunlink('/var/www/*');" should not execute.
If you can provide your users with distinct inputs (if it's a form) go that route.
Thanks Richard Unfortunately it's not that simple. The equation sits in a DB and can be anything - eg. ((([valuation]/[purchaseprice])/100)*100)/[numyears] would be a typical field. [valuation], [purchaseprice] and [numyears] gets replaced by relevant fields from user-entered data. But the system is expandable which means I don't know what the equations, data or fields are going to be beforehand.
Maybe something like this <?php $eq = '((([valuation]/[purchaseprice])/100)*100)/[numyears]'; $valuation = $_GET['valuation']; $purchaseprice = $_GET['purchaseprice']; $numyears = $_GET['numyears']; if ( is_numeric( $valuation ) &&
     is_numeric( $purchaseprice ) &&
     is_numeric( $numyears ) ) {
$eq = str_replace('[valuation]', $valuation, $eq); $eq = str_replace('[purchaseprice]', $purchaseprice, $eq); $eq = str_replace('[numyears]', $numyears, $eq); $result = eval("return {$eq};"); echo $result; } else { echo 'Something failed the number test!'; } ?> Anyone have suggestions on tests that is_numeric() might not catch?
I'm working on some kinda preg_replace function to sanitize the data at the moment and then run an eval - arg I hate regexp! Ideally eval would have some kind of sandboxing option, or you could limit the functions available in an eval. J
-- Jim Lucas "Some men are born to greatness, some achieve greatness, and some have greatness thrust upon them." Twelfth Night, Act II, Scene V by William Shakespeare

« previous php.general (#272841) next »