I was developing some PHP code the other day for a WordPress website and got interrupted. I left halfway through editing a PHP file. When I came back I had lost my train of thought and left a simple syntax error in the file. In a momentary lapse of reason I FTP’ed the file back to the server. The next day I discovered that my website was giving a ‘500 Internal Server Error’ message. Unfortunately this error can have multiple causes.
I went through some of the suggestions in this article: http://www.wpbeginner.com/wp-tutorials/how-to-fix-the-internal-server-error-in-wordpress/ However my problem was not resolved.
I eventually spent ages tracking down the syntax error (at the time I didn’t know that was the cause). I then realised that I could write a script to find all syntax errors in all PHP files on my system. This is the code I wrote.
Automatic PHP Syntax Checker
* Copyright Technology Wales 2015 (http://www.technologywales.co.uk)
* Feel free to adapt this code for personal use. If you do use it then
* please keep this comment block in place.
// Set up some iterators to get us a list of all the PHP files in the specified directory.
$Directory = new RecursiveDirectoryIterator( "c:/wamp/" );
$Iterator = new RecursiveIteratorIterator( $Directory );
$Regex = new RegexIterator( $Iterator, '/^.+\.php$/i', RecursiveRegexIterator::GET_MATCH );
// For each PHP file, do...
foreach ( $Regex as $filename_with_path => $object )
// Create the lint command that will check for syntax errors.
$lint_command = "php -l $filename_with_path";
// Unset the output values from the previous lint command (if any).
unset( $output_array );
unset( $return_value );
// Execute the PHP lint command.
exec( $lint_command, $output_array, $return_value );
// If the lint command found any errors, then...
( $return_value !== 0 ) ||
( strpos( $output_array[ 0 ], 'No Syntax errors detected in' ) !== FALSE )
// Output the syntax errors that were found.
echo "\n\n======================== ERROR! ========================\n";
print_r( $output_array );
echo "RETURN VALUE: $return_value\n\n";
// Otherwise output a dot to let the user know that the current file had no syntax errors.
You could easily run this at the end of every day and get it to email the results to you. That way you can check any errors on the way home. It’s also sensible to run this on your locally developed files before putting them back on the server (or in your version control system).
Example output from this code is as follows. It easily finds the intentional syntax error I put in a test file: