Bill200
Bill200

Reputation: 103

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

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?

Upvotes: 3

Views: 1933

Answers (2)

keidakida
keidakida

Reputation: 741

Your PHP code would throw a 'Notice' kind of error and those cannot be handled by try..catch blocks. You would have to use your own error handlers using PHP's set_error_handler method. Read the document and you will understand what to do. If you want a sample of how to do it then:

<?php

function myErrorHandler($errno, $errstr)
{
    switch ($errno) {
        case E_USER_ERROR:
            die("User Error");
            break;
        default:
            die("Your own error");
            break;
    }

    /* Don't execute PHP internal error handler */
    return true;
}

$err = set_error_handler("myErrorhandler");

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

$result = eval($cmdstr);

echo $three;

?>

Upvotes: 1

Samuel Tallet
Samuel Tallet

Reputation: 166

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;

Upvotes: 4

Related Questions