-3

I have a sample code:

$messages = array(
   array("mark" => "0 < {m} < 4.9", "message" => "BAD"),
   array("mark" => "5 < {m} < 10", "message" => "GOOD"),
);
$m = 3;
$message = "";
foreach ($messages as $row) {
   $condition = $row['mark'];
   $condition = str_replace('{m}', $m, $condition);
   $str = "$result = (bool)".$condition;
   eval($str);
   if($result) $message = $row['message'];
}
echo $message;

Result is BAD, but it show bug: Parse error: syntax error, unexpected '='. How to ideas?

Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102
  • 1
    `$str = "$result = (bool)".$condition;` PHP will attempt to insert the current value of `$result` in your string, not treat it as part of the code you want to eval.... `$str = "\$result = (bool)".$condition;` will force a literal `$` in the code string – Mark Baker Sep 05 '16 at 15:31
  • Compare your code with the examples in the manual about eval(), I'm sure you will see it. – Rizier123 Sep 05 '16 at 15:31
  • 4
    Why `eval` anyway? It's really not needed, or is this a coding exercise? – Yoshi Sep 05 '16 at 15:34
  • When to use `eval` in PHP? Answer: Never. If you think you need to use `eval()` for anything in PHP then you are making a big mistake somewhere. – Simba Sep 05 '16 at 15:39
  • 1
    Using eval() introduces a lot of security risks and performance/capacity issues. The code you've shown us here does not constitute justification for its use - hopefully that's because you've reduxed it down to the minimum necessary code to demonstrate your problem. An alternative to Mark's solution is to do the assignation outside of the eval string via a return within the eval'd string. This makes it easier to manage the code being eval'd (preventing the problem you encountered) and presents the option of parsing/replacing unsafe values (e.g. anything other than a number or an operator). – symcbean Sep 05 '16 at 15:42

1 Answers1

1

Check your code, apart of double quotes: the expression 0 < 3 < 4.9 is not a valid condition in PHP, so you should change it:

$messages = array(
    array("mark" => "0 < {m} && {m} < 4.9;", "message" => "BAD"),
    array("mark" => "5 < {m} && {m} < 10;", "message" => "GOOD"),
);
$m = 3;
$message = "";
foreach ($messages as $row) {
    $condition = $row['mark'];
    $condition = str_replace('{m}', $m, $condition);
    $str = '$result = (bool)'.$condition;
    eval($str);
    if($result) $message = $row['message'];
}
echo $message; //output: BAD
yceruto
  • 9,230
  • 5
  • 38
  • 65