views:

242

answers:

2

I load dynamically PHP class files with autoload. And those files could be missing or corrupted by some reason.

Autoload will successfully report missing files so application logic could handle that. But if those files are corrupted, then the whole processing halts with blank screen for the user and "PHP Parse error: syntax error" in error log.

Is it possible to check syntax of PHP file from PHP code?

I've looked here: http://us.php.net/manual/en/function.php-check-syntax.php - it's deprecated.

And

exec("php -l $file");

seems to be a wrong way (http://bugs.php.net/bug.php?id=46339)

Thoughts?

A: 

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)

Csaba Kétszeri
I assumed he(his system) has no control over those files at build time.
Csaba Kétszeri
Interesting idea, while I think that it is not good to make syntax checking dependant on user visiting the site. Even if only first one will get the blank page.
Sasha Yanovets
+3  A: 

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...

Pascal MARTIN
Thanks for your answer. Answer "no, not with a reasonable performance" is a valid option. SVN pre-commit hook is a great idea and I think will solve our problem in most of the cases.
Sasha Yanovets
You're welcome :-) OK about svn pre-commit hook : when you are admin of the SVN server, hooks are really great to use !
Pascal MARTIN