Command Line Interface Edit on GitHub In category: PHP

Differences to other SAPIs #differences

CLI is a special type of SAPI. Due to this fact, it differs in some ways you should be aware of:

  • No HTTP headers are written to the output (because it doesn't run in the browser);
  • HTML is not parsed (PHP error messages also have HTML tags disabled);
  • Execution time is unlimited;
  • There are no $_POST or $_GET variables.

Accessing user input #user-input

In order to access user input, you can use the following global variables:

  • $argv - array of all arguments/options passed to the script. Its first element ($argv[0]) is the name of executed script itself.
  • $argc - the number of arguments passed to the script; it's an equivalent of equivalent of count($argv) (note it includes the script filename).

if ($argc < 2) {
    echo "Error: This program expects at least one argument.";

You can also use input/output streams. This can be achieved in two ways: opening new stream or using constants STDIN, STDOUT and STDERR, which hold already opened input, output and error streams, respectively.

$stdin = fopen('php://stdin', 'r');

// Predefined constants are file handlers, so you can use them
// with functions like:
$line = trim(fgets(STDIN)); // Reads one line from STDIN

// Operations for other types of streams are performed in the same way


Function getopt() can be very useful when parsing user input to the CLI script.

Checking current SAPI #checking-sapi

No matter if you want to restrict script to be run only using CLI or just customize output depending on destination: browser or terminal - verifying currently used SAPI is very useful possibility.

if (PHP_SAPI !== 'cli') {
    echo "Error: The program should be run from terminal.\n";

You can also use php_sapi_name() as an equivalent of PHP_SAPI constant. Remember that SAPI name is always written in lowercase.

Learn more #learn-more

Comments #comments