How to know that your PHP is borked before your clients kill you

by Richard Bradshaw

Maybe it’s just me, but every now and then I make a quick change to a PHP script, don’t bother checking it, then a few hours/days/months later either realise that I missed a vital semicolon, or mismatched a bracket. This started to get on my nerves, as now this has happened a couple of times I’d like to prevent it from happening again.

After thinking about this a little, and asking the wonderful stackoverflow.com, a person known as okoman suggested using the cli version of PHP to test parse the code using the -l flag.

I quickly wrapped it into a parcel of (ugly) code, set up a cron job to run it as frequently as I estimate I make errors and can now sleep peacefully knowing that all semicolons are in place, and all if’s have the right number of brackets.

So, here’s the delicious file which I’ve placed on my server. You can edit it not to produce output if you’d like and just to send emails/tweets.

<?
function list_dir($dir) {
 
	if (is_dir($dir)) {
		if ($dh = opendir($dir)) {
			while (($file = readdir($dh)) !== false) {
				if (substr("$file", 0, 1) != ".") {
					$files[] = $file;
				}
			}
			closedir($dh);
		}
	}
	sort($files);
	return $files;
}
 
$dir = "/path/to/code//";
$files = list_dir($dir);
$num_files = count($files);
 
for($i=0;$i<$num_files;$i++) {
	if (strpos($files[$i],".php") !== false) {
		$path = $dir.$files[$i];
		$result = `php -l $path`;
 
		if (strpos($result, "Errors parsing") !== false) {
			//tweet_error("Syntax",$files[$i]); //Function in my last post
			mail("emailaddress@example.com","Syntax Error",$files[$i]);
			echo "Syntax error in $files[$i]\n";
		}
	}
}
 
?>

And that’s all there is to it.

To check that it’s working OK, try making a file such as:

<?
if () {
?>

and run the error checking file.

This could be extended by parsing out line numbers and error types, but this minimum setup works for me.

Related Posts