DEV Community

Nick Vahalik
Nick Vahalik

Posted on

Use PHP-Parser to test PHP before eval()

I recently had an issue where I needed to comb through some logs and pull out some data. The data had been logged through Monolog and so it was valid PHP.

Except the logs were corrupt. The logs had been written under a period of heavy load and so some of the entries were corrupt. The file "comber" couldn't detect if the output was valid. But the only way I am aware to actually turn valid PHP into a real PHP structure is eval().

However, eval() presents a problem. If you pass in invalid PHP, you'll get a ParseError and execution will stop.

Enter https://github.com/nikic/PHP-Parser.

By adding this above my call to eval(), I could avoid any corrupt values getting passed through:

use PhpParser\ParserFactory;

$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7)

// ...

try {
    $parser->parse($buffer);
} catch (Error $error) {
    echo "Parse error: {$error->getMessage()}\n";
    return;
}

eval("\$a = $buffer;");

// No more parse errors!

Worked as expected—no more ParseErrors were raised and the logfile combing efforts were successful.

Top comments (0)