I'm wanting to, from PHP 5.2.1, take a string that presumably contains a snippet of php code, and check the syntax of it, but without executing any code, including any files, or interpolating any variables or functions. So basically, I want parse errors.
I've tried a function that wraps the code in an if statement that never executes, and then evals the whole thing, but it still executes includes and requires, and errors out on undefined functions, variables, etc:
function eval_syntax($code) {
$brace_pairs = 0;
// iterate tokens, keeping track of curly braces
foreach (token_get_all($code) as $token) {
if($token == '{') ++$brace_pairs;
else if($token == '}') --$brace_pairs;
}
// return static error on unbalanced braces (will break the eval)
if($brace_pairs) return 'Parse error: mismatched braces';
// eval code in a dead sandbox, catch buffered output
else {
ob_start();
eval('if(0){' . $code . '}');
$out = ob_get_contents();
ob_end_clean();
return empty($out) ? FALSE : $out;
}
}
Ideally, what I want is something that checks basic syntax for parse errors such as unbalanced braces or missing semicolons, and returns some kind of diagnostic information. It shouldn't care about whether variables/classes/constants/functions are defined:
// this should all be ok
print $not_defined_variable;
print NOT_DEFINED_CONSTANT;
$c = new NotDefinedClass();
$f = not_defined_function();
It also shouldn't actually try to execute any included files:
// this should be ok, i dont even care whether these files exist
include('somefile.php');
require('someotherfile.php');
Basically, I just want to check a string containing PHP code, for simple parse errors...is there even a way to do this?