Alena
Alena

Reputation: 179

Is it safe to use "eval"?

I have an input-based string looking like this: "34*(12+45.67)>=44-53" and i need to know if its true or false. So, if the string contains only digits and */+-().<>= is it safe to use eval? Or maybe there is some better solution for this?

Upvotes: 0

Views: 1055

Answers (6)

dave
dave

Reputation: 64657

You could strip out characters you don't want, just to be safe:

$x = preg_replace('/[^0-9+\-\*\/()>=]/', '', $input);
eval($x);

That will remove anything that is not in 0,1,2,3,4,5,6,7,8,9,0,/,+,-,*,(, or )

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

Yes, there is nothing that can be done with that input that is unsafe. So long as you check as follows:

if( preg_match("([^0-9*/+().<>=-])",$input)) die("Invalid input");

Then you will be fine. However, be aware that the input must be syntactically correct. Something like >><>>><><>>>>> would pass the check, but cause an error. You should wrap a try..catch block around your eval.

Ideally, however, this should really be handled in JavaScript if you can. It's okay to use eval on the user's own provided data.

Upvotes: 2

cHao
cHao

Reputation: 86506

If, and only if, that string is

  • built entirely under your control, with no user input being copied in; or
  • already parsed, so that you can guarantee it will always contain only digits and basic math symbols in a valid order;

then eval is safe. Otherwise, at the very least, someone can trigger a parse error.

Upvotes: 0

IanPudney
IanPudney

Reputation: 6021

If your code directly takes the user input and evaluates it:

eval($_POST['myInput'])

then no, it is not safe to use eval. However, you can make it safe to use eval by parsing the string, possibly with a regular expression beforehand,. For example, ensuring that it is composed of only numbers, mathematical operators, and comparison operators will likely do the trick.

Upvotes: 0

Geeky Guy
Geeky Guy

Reputation: 9399

eval is never safe on its own, if you're evaluating user input. If you follow that path, then all security is up to you. If your code has the capacity to mess with sensitive things anywhere, then good luck working out and preventing all the thousands of ways malicious users could screw your application.

Otherwise, if all you have is a sandbox page somewhere that couldn't touch the server to save its life, then yes, you're safe.

Upvotes: 1

Jessica
Jessica

Reputation: 7005

The safety of eval depends on where the data is coming from, and what it contains. If you've confirmed that it only contains digits and mathematical operations, it should be fine.

Note that you would need to parse it and convert it into a PHP statement, as that alone will always return an error. Remember PHP uses == for comparison, and you'll need a variable or two.

Upvotes: 1

Related Questions