Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch a parse error in php eval()?

Tags:

php

I'd like to use php eval() to identify potential parse errors. I'm aware of the dangers of eval, but this is a very limited use which will be fully validated beforehand.

I believe that in php 7 we should be able to catch a parse error, but it doesn't work. Here's an example:

  $one = "hello";
  $two = " world";
  $three = '';
  $cmdstr = '$three = $one . $tw;';

  try {
     $result = eval($cmdstr);
 } catch (ParseError $e) {
     echo 'error: ' . $e;
 }

echo $three;

I'm trying to cause a parse error here to see if I can catch it, but when I run it, the error (undefined variable tw) appears as it usually would. It was not being caught.

Any ideas how to catch a parse error from eval?

like image 651
Bill200 Avatar asked Aug 14 '26 05:08

Bill200


1 Answers

Your code doesn't work as expected because, in PHP, an undefined variable doesn't trigger a parse error but a notice instead. Thanks to set_error_handler native function, you can convert a notice to error then catch it with this PHP 7 code:

<?php

set_error_handler(function($_errno, $errstr) {
    // Convert notice, warning, etc. to error.
    throw new Error($errstr);
});

$one = "hello";
$two = " world";
$three = '';
$cmdstr = '$three = $one . $tw;';

try {
    $result = eval($cmdstr);
} catch (Throwable $e) {
    echo $e; // Error: Undefined variable: tw...
}

echo $three;
like image 173
Samuel Tallet Avatar answered Aug 16 '26 13:08

Samuel Tallet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!