PHP Getting started with PHP PHP CLI

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


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:

  1. Standard input. Run the php command without any arguments, but pipe PHP code into it:
    echo '<?php echo "Hello world!";' | php
  2. Filename as argument. Run the php command with the name of a PHP source file as the first argument:
    php hello_world.php
  3. Code as argument. Use the -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!";'
  4. Interactive shell. Use the -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).

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 1
Stdout 3

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)

Got any PHP Question?