First off, I'm confused on how to run PHP in the command-line. I've been reading several articles on the web and they all say that you need a CLI (Command Line Interface).
Basically, I have PHP files, and I want to call something like this:
php -l somefile.php
But I'm wanting to check a string, not a file! How can this be done? Can using STDIN, STDOUT, or STDERR help with this at all?
If so, how? Can someone provide an example here?
Also, where do I place that above code? I don't have access to a command-line (I don't think), or do I just place it within a PHP file itself that will run? Will it execute this code, in that case, within the command-line?
I'm completely clueless on how this PHP command-line thing works... Can someone please help shed some light on this exactly?
If you want lint code (not within a file) the only option is to write a wrapper.
Assuming your $HOME/bin precedes /usr/bin, you could install your wrapper in $HOME/bin/php that has a different option for command-line linting. The wrapper would create a temporary file, put the code in there, run
/usr/bin/php -l file
and then delete the temporary file.HTH.
You can check code with
php -l
from STDIN by piping it in. Example:Here the ending semicolon
;
is missing after the single quoted string. If you add it, the error goes away and PHP tells you so:The dash
-
inErrors parsing -
orNo 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:BTW, the
-r
switch which is normally intended to provide code for executing, doesn't work in this case and it gives an error: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'sexec
:The output is as follows:
I would suggest checking out phpstan. It is a linter built with PHP, and works a lot like phpunit but for linting code. You can write configs, control linting levels, and include/ignore folders.
It also has proper exit codes.
https://github.com/phpstan/phpstan
If using that isn't possible, I used this script here and it works nicely.