PHP can also be run from command line directly using the CLI (Command Line Interface).
CLI is basically the same as PHP from web servers, except some differences in terms of standard input and output.
The PHP CLI allows four ways to run PHP code:
php
command without any arguments, but pipe PHP code into it: echo '<?php echo "Hello world!";' | php
php
command with the name of a PHP source file as the first argument: php hello_world.php
-r
option in the php
command, followed by the code to run. The <?php
open tags are not required, as everything in the argument is considered as PHP code: php -r 'echo "Hello world!";'
-a
option in the php
command to launch an interactive shell. Then, type (or paste) PHP code and hit return: $ php -a Interactive mode enabled php > echo "Hello world!"; Hello world!
All functions or controls that produce HTML output in web server PHP can be used to produce output in the stdout stream (file descriptor 1), and all actions that produce output in error logs in web server PHP will produce output in the stderr stream (file descriptor 2).
Example.php
<?php
echo "Stdout 1\n";
trigger_error("Stderr 2\n");
print_r("Stdout 3\n");
fwrite(STDERR, "Stderr 4\n");
throw new RuntimeException("Stderr 5\n");
?>
Stdout 6
Shell command line
$ php Example.php 2>stderr.log >stdout.log;\
> echo STDOUT; cat stdout.log; echo;\
> echo STDERR; cat stderr.log\
STDOUT
Stdout 1
Stdout 3
STDERR
Stderr 4
PHP Notice: Stderr 2
in /Example.php on line 3
PHP Fatal error: Uncaught RuntimeException: Stderr 5
in /Example.php:6
Stack trace:
#0 {main}
thrown in /Example.php on line 6
See: Command Line Interface (CLI)