Forum und email

Using PHP from the command line

As of version 4.3.0, PHP supports a new SAPI type (Server Application Programming Interface) named CLI which means Command Line Interface. As the name implies, this SAPI type main focus is on developing shell (or desktop as well) applications with PHP. There are quite a few differences between the CLI SAPI and other SAPIs which are explained in this chapter. It's worth mentioning that CLI and CGI are different SAPI's although they do share many of the same behaviors.

The CLI SAPI was released for the first time with PHP 4.2.0, but was still experimental and had to be explicitly enabled with --enable-cli when running ./configure. Since PHP 4.3.0 the CLI SAPI is no longer experimental and the option --enable-cli is on by default. You may use --disable-cli to disable it.

As of PHP 4.3.0, the name, location and existence of the CLI/CGI binaries will differ depending on how PHP is installed on your system. By default when executing make, both the CGI and CLI are built and placed as sapi/cgi/php and sapi/cli/php respectively, in your PHP source directory. You will note that both are named php. What happens during make install depends on your configure line. If a module SAPI is chosen during configure, such as apxs, or the --disable-cgi option is used, the CLI is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if --with--apxs is in your configure line then the CLI is copied to {PREFIX}/bin/php during make install. If you want to override the installation of the CGI binary, use make install-cli after make install. Alternatively you can specify --disable-cgi in your configure line.

Note: Because both --enable-cli and --enable-cgi are enabled by default, simply having --enable-cli in your configure line does not necessarily mean the CLI will be copied as {PREFIX}/bin/php during make install.

The Windows packages between PHP 4.2.0 and PHP 4.2.3 distributed the CLI as php-cli.exe, living in the same folder as the CGI php.exe. Starting with PHP 4.3.0 the Windows package distributes the CLI as php.exe in a separate folder named cli, so cli/php.exe . Starting with PHP 5, the CLI is distributed in the main folder, named php.exe. The CGI version is distributed as php-cgi.exe.

As of PHP 5, a new php-win.exe file is distributed. This is equal to the CLI version, except that php-win doesn't output anything and thus provides no console (no "dos box" appears on the screen). This behavior is similar to php-gtk. You should configure with --enable-cli-win32.

Note: What SAPI do I have? From a shell, typing php -v will tell you whether php is CGI or CLI. See also the function php_sapi_name() and the constant PHP_SAPI.

Note: A Unix manual page was added in PHP 4.3.2. You may view this by typing man php in your shell environment.

Remarkable differences of the CLI SAPI compared to other SAPIs:

  • Unlike the CGI SAPI, no headers are written to the output.

    Though the CGI SAPI provides a way to suppress HTTP headers, there's no equivalent switch to enable them in the CLI SAPI.

    CLI is started up in quiet mode by default, though the -q and --no-header switches are kept for compatibility so that you can use older CGI scripts.

    It does not change the working directory to that of the script. (-C and --no-chdir switches kept for compatibility)

    Plain text error messages (no HTML formatting).

  • There are certain php.ini directives which are overridden by the CLI SAPI because they do not make sense in shell environments:

    Overridden php.ini directives
    Directive CLI SAPI default value Comment
    html_errors FALSE It can be quite hard to read the error message in your shell when it's cluttered with all those meaningless HTML tags, therefore this directive defaults to FALSE.
    implicit_flush TRUE It is desired that any output coming from print(), echo() and friends is immediately written to the output and not cached in any buffer. You still can use output buffering if you want to defer or manipulate standard output.
    max_execution_time 0 (unlimited) Due to endless possibilities of using PHP in shell environments, the maximum execution time has been set to unlimited. Whereas applications written for the web are often executed very quickly, shell application tend to have a much longer execution time.
    register_argc_argv TRUE

    Because this setting is TRUE you will always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments) in the CLI SAPI.

    As of PHP 4.3.0, the PHP variables $argc and $argv are registered and filled in with the appropriate values when using the CLI SAPI. Prior to this version, the creation of these variables behaved as they do in CGI and MODULE versions which requires the PHP directive register_globals to be on. Regardless of version or register_globals setting, you can always go through either $_SERVER or $HTTP_SERVER_VARS. Example: $_SERVER['argv']

    Note: These directives cannot be initialized with another value from the configuration file php.ini or a custom one (if specified). This is a limitation because those default values are applied after all configuration files have been parsed. However, their value can be changed during runtime (which does not make sense for all of those directives, e.g. register_argc_argv).

  • To ease working in the shell environment, the following constants are defined:

    CLI specific Constants
    Constant Description
    STDIN

    An already opened stream to stdin. This saves opening it with

    <?php

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

    ?>
    If you want to read single line from stdin, you can use
    <?php
    $line 
    trim(fgets(STDIN)); // reads one line from STDIN
    fscanf(STDIN"%d\n"$number); // reads number from STDIN
    ?>

    STDOUT

    An already opened stream to stdout. This saves opening it with

    <?php

    $stdout 
    fopen('php://stdout''w');

    ?>

    STDERR

    An already opened stream to stderr. This saves opening it with

    <?php

    $stderr 
    fopen('php://stderr''w');

    ?>

    Given the above, you don't need to open e.g. a stream for stderr yourself but simply use the constant instead of the stream resource:

    php -r 'fwrite(STDERR, "stderr\n");'
    
    You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends.

    Note: These constants are not available in case of reading PHP script from stdin.

  • The CLI SAPI does not change the current directory to the directory of the executed script!

    Example showing the difference to the CGI SAPI:

    <?php
    // Our simple test application named test.php
    echo getcwd(), "\n";
    ?>

    When using the CGI version, the output is:

    $ pwd
    /tmp
    
    $ php -q another_directory/test.php
    /tmp/another_directory
    

    This clearly shows that PHP changes its current directory to the one of the executed script.

    Using the CLI SAPI yields:

    $ pwd
    /tmp
    
    $ php -f another_directory/test.php
    /tmp
    

    This allows greater flexibility when writing shell tools in PHP.

    Note: The CGI SAPI supports this CLI SAPI behaviour by means of the -C switch when run from the command line.

The list of command line options provided by the PHP binary can be queried anytime by running PHP with the -h switch:

Usage: php [options] [-f] <file> [--] [args...]
       php [options] -r <code> [--] [args...]
       php [options] [-B <begin_code>] -R <code> [-E <end_code>] [--] [args...]
       php [options] [-B <begin_code>] -F <file> [-E <end_code>] [--] [args...]
       php [options] -- [args...]
       php [options] -a

  -a               Run interactively
  -c <path>|<file> Look for php.ini file in this directory
  -n               No php.ini file will be used
  -d foo[=bar]     Define INI entry foo with value 'bar'
  -e               Generate extended information for debugger/profiler
  -f <file>        Parse and execute <file>.
  -h               This help
  -i               PHP information
  -l               Syntax check only (lint)
  -m               Show compiled in modules
  -r <code>        Run PHP <code> without using script tags <?..?>
  -B <begin_code>  Run PHP <begin_code> before processing input lines
  -R <code>        Run PHP <code> for every input line
  -F <file>        Parse and execute <file> for every input line
  -E <end_code>    Run PHP <end_code> after processing all input lines
  -H               Hide any passed arguments from external tools.
  -s               Display colour syntax highlighted source.
  -v               Version number
  -w               Display source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

  args...          Arguments passed to script. Use -- args when first argument
                   starts with - or script is read from stdin

  --ini            Show configuration file names

  --rf <name>      Show information about function <name>.
  --rc <name>      Show information about class <name>.
  --re <name>      Show information about extension <name>.
  --ri <name>      Show configuration for extension <name>.

The CLI SAPI has three different ways of getting the PHP code you want to execute:

  1. Telling PHP to execute a certain file.

    php my_script.php
    
    php -f my_script.php
    

    Both ways (whether using the -f switch or not) execute the file my_script.php. You can choose any file to execute - your PHP scripts do not have to end with the .php extension but can have any name or extension you wish.

    Note: If you need to pass arguments to your scripts you need to pass -- as the first argument when using the -f switch.

  2. Pass the PHP code to execute directly on the command line.

    php -r 'print_r(get_defined_constants());'
    

    Special care has to be taken in regards of shell variable substitution and quoting usage.

    Note: Read the example carefully, there are no beginning or ending tags! The -r switch simply does not need them. Using them will lead to a parser error.

  3. Provide the PHP code to execute via standard input (stdin).

    This gives the powerful ability to dynamically create PHP code and feed it to the binary, as shown in this (fictional) example:

    $ some_application | some_filter | php | sort -u >final_output.txt
    
You cannot combine any of the three ways to execute code.

Like every shell application, the P