Newbie
Newbie

Reputation: 153

Eval is discouraged in php 7

I am getting formula in string foe example

$a = '1*2*(2+3)';
echo eval($a) // Output should be 10

Now i am trying to evaluate this string and use eval for that but in php 7 give me this error Use of eval() is discouraged so how can i evaluate this string.

Upvotes: 2

Views: 4147

Answers (3)

Seb33300
Seb33300

Reputation: 7556

You cannot use echo on eval() unless you use return in the evaluated code.

eval() returns NULL unless return is called in the evaluated code

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

So you can do:

$a = 'echo 1*2*(2+3);';
eval($a);

or

$a = 'return 1*2*(2+3);';
echo eval($a);

Upvotes: 1

Joe Watkins
Joe Watkins

Reputation: 17148

PHP never raises any such error: You should be suspicious that a third party has interfered with the installation, possibly installed some kind of "security" focused extension that changes the behaviour of PHP.

All such extensions are not sanctioned by the PHP project, and are terrible.

Despite what the manual says about eval, there is no technical difference between including a file, and evaling some code.

The only difference in the real world is that eval'd code may contain user input: The sanitization and filtering of user input is a problem for PHP applications that do not use eval.

Note: you are missing a return from the evaluated expression

Upvotes: 6

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

The manual says;

Caution

The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

As far as the alternative is concerned you can try this solution given in the thread: calculate math expression from a string using eval

Upvotes: 0

Related Questions