Home / PHP command line syntax checking

PHP command line syntax checking

The PHP CLI (command line interface) allows basic syntax checking of a PHP file. I’ll show the basic usage of this in this post and then a couple of ways to check all files in a directory, and all files recursively down the directory tree as posted by a couple of people on Twitter.

Syntax checking a single PHP file from the command line

The syntax for checking is like this, where the -l flag is a lower case L:

php -l filename

If the syntax in the file is correct you will see this:

No syntax errors detected in test.php

If there are errors then theses will be listed as in the following example output:

Parse error: syntax error, unexpected T_STRING in test.php on line 5
Errors parsing test.php

Note that the syntax checking only checks for syntax errors – it does not report the usage of variables which have not yet been defined, functions or class which have not be declared etc.

So something like this will pass:

<?php
echo $x;
call_a_function_that_does_not_exist();

but these will not:

<?php
$x => 1;
something {
}

Syntax check all PHP files in the current directory

This was posted by @chrisvoo (http://twitter.com/chrisvoo) to syntax check all the PHP files (or at least all files with a .php extension) in the current directory from a BASH command line:

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

Syntax check all PHP files in the current directory and all subdirectories

I retweeted the above and was replied to by @gurubobnz on Twitter (http://twitter.com/gurubobnz) with how to syntax check all .php files recursively down the directory tree from current directory:

find . -name *.php -exec php -l "{}" ;

Thanks to @chrisvoo and @gurubobnz

Thanks to @chrisvoo and @gurubobnz for posting these on Twitter – they are very useful!