a few words about web development

PHP: How to safely include file with possible parse errors?

Another straight to the point solution
Recently I had written a class and it had to save bits of information somewhere. I wanted to make the script installable just by placing it on a server so I didn't want to use any database. Instead I figured out I should save the data in a simple file. I could use serialize and file_put_contents which is very easy to write, but modifying such files manually in a text editor is a nightmare. So I decided to save the contents in a PHP file.
Unfortunately if there is an error in such file you will get parse error when including it.
Solution? Pretty simple- check the file before including it.
To check such file you can use php_check_syntax in PHP 5.0.4-. You can also use exec/system and run "php -l filename.php" command which works even in PHP newer than 5.04.

Here's a snippet you can use:
$res = exec("php -l datafile.php");
if (strstr($res, "No syntax errors detected"))
{		
	include_once 'datafile.php';
}
else //alternatively load a "safe" file:
{
	include_once 'datafile.backup.php';
}

Comments