note 24571 added to function.eval
| From: | johnmott59 at hotmail dot com | Date: | Wed, 21 Aug 2002 21:15:34 +0000 |
| Subject: | note 24571 added to function.eval | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-35319@lists.php.net to get a copy of this message | ||
eval is nice for handling user calculations instead of writing a recursive descent parser. The note
above warns about the dangers of this, but by value checking the expression you can be ok.
I allow users to enter an expression with one of 9 variables named 'q1' to 'q9'.
They can use the arithmetic operators, digits and the 'q' variables. Before executing the
eval() I convert all of those things to blanks in a copy of the expression. If anything is left over
its an invalid expression and I don't execute it.
/*
* Validate, this string should only contain digits, operators and q variables
*/
$sTemp = strtolower($formula);
$pat = "(q1|q2|q3|q4|q5|q6|q7|q8|q9)";
$replace = "";
$sTemp = ereg_replace($pat,$replace,$sTemp);
/*
* Convert digits and operators to blank
*/
$sTemp = strtr($sTemp,"0123456789-+/*()"," ");
/*
* If the calculation isn't null its invalid
*/
if (trim($sTemp) != "") $result = "<font color=red> Invalid calculation
</font>";
--
http://www.php.net/manual/en/function.eval.php
http://master.php.net/manage/user-notes.php?action=edit+24571
http://master.php.net/manage/user-notes.php?action=delete+24571
http://master.php.net/manage/user-notes.php?action=reject+24571