You can check code with php -l
from STDIN by piping it in. Example:
$ echo "<?php echo 'hello world'" | php -l
Parse error: syntax error, unexpected end of file, expecting ',' or ';' in - on line 2
Errors parsing -
Here the ending semicolon ;
is missing after the single quoted string. If you add it, the error goes away and PHP tells you so:
$ echo "<?php echo 'hello world';" | php -l
No syntax errors detected in -
The dash -
in Errors parsing -
or No syntax errors detected in -
stands for STDIN. It's commonly used for that.
Another way is to write the code you want to lint your own (or copy and paste it). This works by using the lint switch with --
, entering the code and finishing it by entering Ctrl + D (Linux) / Ctrl + Z (Win) on a line of its own:
$ php -l --
<?php echo "1"
^Z
Parse error: syntax error, unexpected end of file, expecting ',' or ';' in - on line 2
Errors parsing -
BTW, the -r
switch which is normally intended to provide code for executing, doesn't work in this case and it gives an error:
$ php -l -r "echo 1"
Either execute direct code, process stdin or use a file.
Most likely because it is intended for running code and thats it for, no linting. Also it is without the opening PHP tag.
From all these options, the first one makes probably most sense if you want to pipe it in (you could also operate with proc_open
in case you need more control). Here is a quick example using PHP's exec
:
<?php
/**
* PHP Syntax Checking with lint and how to do this on a string, NOT a FILE
*
* @link http://stackoverflow.com/q/12152765/367456
* @author hakre
*/
$code = "<?php echo 'hello world'";
$result = exec(sprintf('echo %s | php -l', escapeshellarg($code)), $output, $exit);
printf("Parsing the code resulted in; %s\n", $result);
echo "The whole output is:\n";
print_r($output);
The output is as follows:
Parsing the code resulted in; Errors parsing -
The whole output is:
Array
(
[0] =>
[1] => Parse error: syntax error, unexpected '"', expecting ',' or ';' in - on line 1
[2] => Errors parsing -
)