This article will quickly run through the ways PHP can be used from the Bash shell/command line, with examples.
PHP is usually used for generating content to be served on the web – but it can also be used from the command line.
This is usually done for the purposes of testing or finding out information about the PHP environment – but PHP can also be used for writing command-line scripts (though, again, it’s not really done that frequently – probably because there are better alternatives).
Execute a PHP Command Directly From the Shell
PHP commands can be executed directly from the command line with the -r (run) option:
php -r 'phpinfo();'
Above, the phpinfo() function is called. Multiple lines of code can be passed separated by a semicolon, or a heredoc (multiline Bash variable) can be piped in.
Parameters/Arguments
Parameters/Arguments can be passed to PHP using the $argv variable, which is available when PHP is executed from the command line.
php -r 'echo $argv[1]; echo $argv[2];' "foo" "bar"
Above, the first parameter is accessed using $argv[1] and the second parameter using $argv[2].
$argv is an array that will only be accessible if PHP is called from the command line. The first item in the array will be the name of the PHP executable called to execute the script, and the following items in the array will be the parameters passed in order of appearance.
Execute a Script File
PHP files can be executed from the command line by supplying the path to the file:
php script.php
or
php -f script.php
The -f option is not required but can be specified for clarity.
A full list of the PHP command-line options can be found here.
Parameters/Arguments
As when executing PHP directly from the command line, parameters can be accessed using the $argv array when running scripts from the command line in the same way.
Checking if Running From the Command Line
Like $argv, $argc is only present when running from the command line. It contains the number of parameters/arguments passed to the script.
If it is present, you’re running on the command line!
if (isset($argc)) { // PHP was called from the command line }
STDIN/STDOUT and PHP
echo 'Green trees' | php -r 'echo file_get_contents("php://stdin");'
Above, the text ‘Green trees’ is piped to PHP, which then reads the files of STDIN and repeats it back.