0

I use eval('1+1') without any issue in JavaScript but for some reason I can't get this to work in PHP. This is an internal (non-public) webpage so security is not an issue. No matter how I code it I am seeing an 500 Internal Server Error.

I'm trying to do something like this in a PHP file:

$expression='1+1';

echo "eval($expression)";

Is the eval() function in PHP not the same as the JavaScript equivalent or is it perhaps not as straightforward to implement?

4

5 回答 5

1

You have the following code:

$expression='1+1';
echo "eval($expression)";

Since you're quoting the eval() statement, it'd just print eval(1+1) literally.

eval() needs a valid expression.

You're probably looking for:

$expression='1+1'; 
echo eval("echo $expression;");

Demo!

于 2013-10-19T07:54:42.173 回答
1

eval() function must have as argument a valid php code, see this example:

echo eval("return 1+1;");
于 2013-10-19T08:07:25.543 回答
0

http://php.net/manual/en/function.eval.php

Note that the eval() function is very dangerous, regardless of internal server or not, be careful.

Now, eval() in PHP allows executing of PHP code. What you're doing is echoing executing PHP code.

That said, try this:

$expression = "1+1";
echo eval("echo $expression;");
于 2013-10-19T07:53:44.013 回答
0

eval() executes PHP code, not just about anything like any arbitrary mathematical expression. 1+1 is not a valid PHP code expression. So give it proper PHP expression to execute. like:

$expression='echo 1+1;'; 
eval($expression);

Valid PHP code to be evaluated.

Reference

于 2013-10-19T07:55:30.243 回答
0

Try this,

eval('$expression =1+1;');
echo $expression;
于 2013-10-19T07:57:47.930 回答