在PHP中检查PHP文件是否有语法错误的方法

2019-04-10 03:00:40王振洲

checker.php

<?php

if(!function_exists('php_check_syntax')) {
function php_check_syntax($file_name, &$error_message = null) {
$file_content = file_get_contents($file_name);

$check_code = "return true; ?>";
$file_content = $check_code . $file_content . "<?php ";

if(!@eval($file_content)) {
$error_message = "file: " . realpath($file_name) . " have syntax error";
return false;
}

return true;
}
}

if(!php_check_syntax("file.php", $msg)) {
echo $msg;
}
else {
echo "Woohoo, OK!";
}

file.php

<?php
foreach:: a => b
?>

因为Parse error 是没法被 set_error_handler处理函数处理的。这个异常没办法catch到。所以才使用了@来抑制错误。这带来的问题就是我们无法得到详细的错误信息。 不过目前我需要的功能也只是检查语法是否正确。不正确的话重新编译模板文件,就这么简单,至于语法错误,在显示网页的时候自然会看得到。
最好的办法就是这个被遗弃的php_check_syntax这个方法回到php中。下次再研究下他们是出于什么原因把这个函数去掉的。
////////思维很混乱,写的每一点条理性,谁让我语文那么烂涅。
相关文章 大家在看