PHP CLI
suggest changePHP 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.
Triggering
The PHP CLI allows four ways to run PHP code:
- Standard input. Run
phpwith no arguments and pipe code into it:echo '<?php echo "Hello world!";' | php - Filename as argument. Pass the source file:
php hello_world.php - Code as argument.
-rtakes PHP code, with no opening<?phptag:php -r 'echo "Hello world!";' - Interactive shell.
php -aneeds the readline extension. At thephp >prompt, typeecho "Hello world!";and press return.
Output
Output that would be HTML on a web server goes to stdout (file descriptor 1). With display_errors=stderr, which is the usual CLI default, notices and fatal errors go to stderr (file descriptor 2). With display_errors=On, those messages go to stdout, and only an explicit fwrite(STDERR, ...) stays on stderr. The text Stdout 6 never appears: the exception ends the script first.
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
Notice: Stderr 2
in Example.php on line 3
Stderr 4
Fatal error: Uncaught RuntimeException: Stderr 5
in Example.php:6
Stack trace:
#0 {main}
thrown in Example.php on line 6
The path is wherever Example.php actually is. PHP 8 reports Notice: and Fatal error:; older PHP prefixed those lines with PHP.
Input
See the command line section of the PHP manual.