php validator in php?

Hello, I have a question. I’ll make a reservation right away – pure interest, but it can be practically useful to someone. In general, is such a problem solvable: take the code (file/db/variable, it doesn’t matter) and if it is validexecute(eval)?

I.e. the question is precisely in checking whether it is possible to somehow check the variable for the content of the working / syntactically correct code using php?

<?
$code = file_get_contents('very.suspicious.code.php');
if (isValidPhpCode($code)) {
  eval('?'.'>'.$code.'<'.'?');
  } else echo '<p><b>Error:</b> code is invalid</p>';
?>

Answer 1, authority 100%

Syntax validity can be checked via the console command php -l

$file = 'very.suspicious.code.php';
$cmd = 'php -l '.escapeshellarg($file).' 2>&1 >/dev/null';
exec($cmd, $errors, $return);
if ($return === 0) {
    // no syntax errors
} else {
    echo implode("\n", $errors)."\n";
}

Or if the code is contained in a variable, then through pipes

function check_syntax($code, $withoutOpenTag = false, &$error = null) {
    if ($withoutOpenTag) {
        $code = '<?php '.$code;
    }
    $spec = array(
        0 => array('pipe', 'r'),
        1 => array('file', '/dev/null', 'w'),
        2 => array('pipe', 'w')
    );
    $proc = proc_open('php -l', $spec, $pipes);
    fwrite($pipes[0], $code);
    fclose($pipes[0]);
    $error = stream_get_contents($pipes[2]);
    fclose($pipes[2]);
    return proc_close($proc) === 0;
}
$code = '$a = 1 2;';
if (check_syntax($code, true, $error)) {
    // no syntax errors
} else {
    echo $error;
}