Check PHP syntax from the command line

PHP command-line interface (CLI) includes a nifty option to quickly check for any syntax errors in a source code file. A simple check for a single file is given below. The option flag to check is -l (lowercase ‘L’).

$ php -l example.php

If the file contains no syntax errors, the CLI returns the following message.

No syntax errors detected in example.php

If there is an error in the code the CLI will return the error depending on the context of the error.

Parse error: syntax error, unexpected '$dom' (T_VARIABLE) in example.php on line 6
Errors parsing example.php

We can also test for multiple PHP files in the current directory using a BASH shell command.

$ for i in *.php; do php -l $i; done

This will test all the PHP files in the current directory for any syntax errors and report the same.

On Windows you can use the following in the command windows to check for the same. Assuming that your command window is in the directory where the PHP files are located.

c:\localhost\test\> for %x in (*.php) do @php -l "%x"

Besides returning a message, the shell also returns a exit code of ‘-1’ if the checking fails or a ‘0’ if no errors are found. This can be useful if you want to test it via a shell script or another PHP program.

Leave a Reply

Your email address will not be published. Required fields are marked *