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
$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... if ( ( $return_value !== 0 ) || ( strpos( $output_array[ 0 ], 'No Syntax errors detected in' ) !== FALSE ) ) { // Output the syntax errors that were found. echo "\n$lint_command"; echo "\n\n======================== ERROR! ========================\n"; echo "OUTPUT:\n"; print_r( $output_array ); echo "RETURN VALUE: $return_value\n\n"; } else { // Otherwise output a dot to let the user know that the current file had no syntax errors. echo '.'; } } echo "\n"; ?>
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: