Is it possible to check PHP file syntax from PHP?

a 夏天 提交于 2019-12-05 01:37:31

You really shouldn't try to check for non-correct PHP files at execution time : it'll kill the response time of your application !

A "better way" would be to use php -l from command line when you're done modifying a PHP script ; or include it in your build process if you're using one ; or plug it as an SVN pre-commit hook if you're using SVN and can define SVN hooks.

In my opinion, almost any given solution would be better than checking that yourself at execution time !


Considering errors like the ones you want to avoid will probably won't happen often, it is probably better to... just let them happen.
ONly thing is : activate logs, and monitor them, the be able to detect quickly when tere is a problem :-)


Of course, this doesn't prevent you from dealing with the case of missing files ; but that's a different matter...

Another way you can make one php file in your root directory called checkSyntax.php

<?php
for($i=1; $i < count($argv); $i++){
        $temp = "php -l " . $argv[$i];
        $output = exec($temp);
        echo "\n$output";
}
?>

now, open your bashrc file to make a shortcut to run this file. add below line to run checkSyntax.php

alias checkSyntaxErrors='php /root/checkSyntax.php'

and now goto your source directory do svn st.

it shows you list of files, now easily run the command.

checkSyntaxErrors file1.php file2.php .......

this will check all your files passing as arguments.

enjoy :)

In short: i can't see a way to do this, but have an idea which might be sufficient.

There are log monitoring programs or can filter the logs via standard tools for files with parse errors. If a file appears, you put the villain filename into a black list and your autoloader checks before load against this list.

With this method, at first time you'll serve a blank screen (assumig error reporting to the output are turned on on production servers) but the second will have a page without the faulty component.

In the autoloader you should have a list or naming scheme to always try to loading mandatory classes (other ways your application might be in an inconsistent state)

You could also do some unit testing, where you load the PHP you're dynamically executing and assert that exec("php -l $fileName") is valid. If you did that you'd be able to verify it once in your tests, generating it with appropriate variables, and have a reasonable level of confidence your PHP was good.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!