0

(Please note, it's been user entered, so I cannot hard code it). Anyways, the user enters math.php?do=2+2 and the script will kick back 4 as a result. Another thing is that the input is rigorously verified, so, there is no malicious possibility. My testing method is this

function testMath($char){
    $array['math'] = Array("+", "-", "/", "*", "(", ")", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    foreach($char as $chr){
        if(!in_array($chr, $array['math'){
            return false;
        }
    }
    return true;
}

Would it be safe to eval() something checked by this? or should I forget about doing math from user-entered input?

Side note, PHP throws

Parse error: parse error in C:\Users\Josh\Desktop\App\html\new.php(24) : eval()'d code on line 1

When I try to eval() something. What's wrong?

Rebecca
  • 700
  • 2
  • 8
  • 19
  • 5
    Why wouldn't you just do the math on the user's end with javascript? way less risky – Andy Ray Dec 11 '11 at 07:58
  • `eval` has some obvious safety problems if it's done on user input .. your test seems okay, but you may want to limit the length as well. What does it look like when you call `eval`? – Explosion Pills Dec 11 '11 at 08:06
  • 1
    Or use something that's already been created: http://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php – NightHawk Dec 11 '11 at 08:07

1 Answers1

1

I'm not sure how you used the eval() since you didn't post that part of your code. But if you are going to eval the code, you need to specify the variable it will be saved to:

Revised testMath:

function testMath($char){
    if(strlen($char) > 10) return false;
    $array['math'] = Array("+", "-", "/", "*", "(", ")", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    foreach($char as $chr){
        if(!in_array($chr, $array['math'){
            return false;
        }
    }
    return true;
}

$math = $_GET['do'];
if(testMath($math)) eval("$result = " . $math . ";");

echo $math, ' = ', $result;
dchrastil
  • 582
  • 3
  • 5