Using PHP from the command line Command line usage
Introduction The main focus of &cli.sapi; is for developing shell applications with PHP. There are quite a few differences between the &cli.sapi; and other SAPIs which are explained in this chapter. It is worth mentioning that &cli; and CGI are different SAPIs although they do share many of the same behaviors. The &cli.sapi; is enabled by default using , but may be disabled using the option when running ./configure. 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-cgi 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 option is used, the &cli; is copied to {PREFIX}/bin/php during make install otherwise the CGI is placed there. So, for example, if 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 in your configure line. Because both and are enabled by default, simply having in your configure line does not necessarily mean the &cli; will be copied as {PREFIX}/bin/php during make install. As of PHP 5, the &cli; binary is distributed in the main folder as php.exe on Windows. The CGI version is distributed as php-cgi.exe. Additionally, a php-win.exe is distributed if PHP is configured using . This does the same as the &cli; version, except that it doesn't output anything and thus provides no console. 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. A Unix manual page is available by typing man php in the shell environment.
Differences to other <acronym>SAPI</acronym>s 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 and switches are kept for compatibility so that it is possible to use older CGI scripts. It does not change the working directory to that of the script. ( and 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; Defaults to &false;, as it can be quite hard to read error messages in the shell enviroment when they are cluttered up with uninterpreted HTML tags. implicit_flush &true; In a shell environment, it is usually desirable for output, such as from print, echo and friends, to be displayed immediately, and not held in a buffer. Nonetheless, it is still possible to use output buffering to defer or manipulate standard output. max_execution_time 0 (unlimited) PHP in a shell environment tends to be used for a much more diverse range of purposes than typical Web-based scripts, and as these can be very long-running, the maximum execution time is set to unlimited. register_argc_argv &true; Setting this to &true; means that scripts executed via the &cli; SAPI always have access to argc (number of arguments passed to the application) and argv (array of the actual arguments). The PHP variables $argc and $argv are automatically set to the appropriate values when using the &cli; SAPI. These values can also be found in the $_SERVER array, for example: $_SERVER['argv']. output_buffering &false; Although the &php.ini; setting is hardcoded to &false;, the Output buffering functions are available. max_input_time &false; The PHP &cli; does not support GET, POST or file uploads.
These directives cannot be initialized with another value from the configuration file &php.ini; or a custom one (if specified). This limitation is because the values are applied after all configuration files have been parsed. However, their values can be changed during runtime (although this is not sensible for all of them, such as register_argc_argv). It is recommended to set ignore_user_abort for command line scripts. See ignore_user_abort for more information.
To ease working in the shell environment, a number of constants are defined for I/O streams . The &cli.sapi; does not change the current directory to the directory of the executed script. Example showing the difference to the <acronym>CGI</acronym> <acronym>SAPI</acronym>: ]]> When using the CGI version, the output is: This clearly shows that PHP changes its current directory to the one of the executed script. Using the &cli.sapi; yields: This allows greater flexibility when writing shell tools in PHP. The CGI SAPI supports this &cli.sapi; behaviour by means of the switch when run from the command line.
Command line options Options The list of command line options provided by the PHP binary can be queried at any time by running PHP with the switch: [--] [args...] php [options] -r [--] [args...] php [options] [-B ] -R [-E ] [--] [args...] php [options] [-B ] -F [-E ] [--] [args...] php [options] -- [args...] php [options] -a -a Run interactively -c | 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 Parse and execute . -h This help -i PHP information -l Syntax check only (lint) -m Show compiled in modules -r Run PHP without using script tags -B Run PHP before processing input lines -R Run PHP for every input line -F Parse and execute for every input line -E Run PHP after processing all input lines -H Hide any passed arguments from external tools. -S : Run with built-in web server. -t Specify document root for built-in web server. -s Output HTML syntax highlighted source. -v Version number -w Output source with stripped comments and whitespace. -z Load Zend extension . args... Arguments passed to script. Use -- args when first argument starts with - or script is read from stdin --ini Show configuration file names --rf Show information about function . --rc Show information about class . --re Show information about extension . --rz Show information about Zend extension . --ri Show configuration for extension . ]]> Command line options Option Long Option Description -a --interactive Run PHP interactively. For more information, see the Interactive shell section. -b --bindpath Bind Path for external FASTCGI Server mode (CGI only). -C --no-chdir Do not chdir to the script's directory (CGI only). -q --no-header Quiet-mode. Suppress HTTP header output (CGI only). -T --timing Measure execution time of script repeated count times (CGI only). -c --php-ini Specifies either a directory in which to look for &php.ini;, or a custom INI file (which does not need to be named &php.ini;), e.g.: If this option is not specified, &php.ini; is searched for in the default locations. -n --no-php-ini Ignore &php.ini; completely. -d --define Set a custom value for any of the configuration directives allowed in &php.ini;. The syntax is: -e --profile-info Activate the extended information mode, to be used by a debugger/profiler. -f --file Parse and execute the specified file. The is optional and may be omitted - providing just the filename to execute is sufficient. To pass arguments to a script, the first argument must be --, otherwise PHP will interpret them as PHP options. -h and -? --help and --usage Output a list of command line options with one line descriptions of what they do. -i --info Calls phpinfo, and prints out the results. If PHP is not working correctly, it is advisable to use the command php -i and see whether any error messages are printed out before or in place of the information tables. Beware that when using the CGI mode the output is in HTML and therefore very large. -l --syntax-check Provides a convenient way to perform only a syntax check on the given PHP code. On success, the text No syntax errors detected in <filename> is written to standard output and the shell return code is 0. On failure, the text Errors parsing <filename> in addition to the internal parser error message is written to standard output and the shell return code is set to -1. This option won't find fatal errors (like undefined functions). Use the to test for fatal errors too. This option does not work together with the option. -m --modules Printing built in (and loaded) PHP and Zend modules -r --run Allows execution of PHP included directly on the command line. The PHP start and end tags (<?php and ?>) are not needed and will cause a parse error if present. Care must be taken when using this form of PHP not to collide with command line variable substitution done by the shell. Getting a syntax error when using double quotes The problem here is that sh/bash performs variable substitution even when using double quotes ". Since the variable $foo is unlikely to be defined, it expands to nothing which results in the code passed to PHP for execution actually reading: The correct way would be to use single quotes '. Variables in single-quoted strings are not expanded by sh/bash. Using single quotes to prevent the shell's variable substitution int(1) ["E_WARNING"]=> int(2) ["E_PARSE"]=> int(4) ["E_NOTICE"]=> int(8) ["E_CORE_ERROR"]=> [...] ]]> If using a shell other than sh/bash, further issues might be experienced - if appropriate, a bug report should be opened at &url.php.bugs;. It is still easy to run into trouble when trying to use variables (shell or PHP) in commnad-line code, or using backslashes for escaping, so take great care when doing so. You have been warned! is available in the &cli.sapi;, but not in the CGI SAPI. This option is only intended for very basic code, so some configuration directives (such as auto_prepend_file and auto_append_file) are ignored in this mode. -B --process-begin PHP code to execute before processing stdin. Added in PHP 5. -R --process-code PHP code to execute for every input line. Added in PHP 5. There are two special variables available in this mode: $argn and $argi. $argn will contain the line PHP is processing at that moment, while $argi will contain the line number. -F --process-file PHP file to execute for every input line. Added in PHP 5. -E --process-end PHP code to execute after processing the input. Added in PHP 5. Using the <option>-B</option>, <option>-R</option> and <option>-E</option> options to count the number of lines of a project. -S --server Starts built-in web server. Available as of PHP 5.4.0. -t --docroot Specifies document root for built-in web server. Available as of PHP 5.4.0. -s --syntax-highlight and --syntax-highlighting Display colour syntax highlighted source. This option uses the internal mechanism to parse the file and writes an HTML highlighted version of it to standard output. Note that all it does is generate a block of <code> [...] </code> HTML tags, no HTML headers. This option does not work together with the option. -v --version Using <option>-v</option> to get the <acronym>SAPI</acronym> name and the version of PHP and Zend -w --strip Display source with comments and whitespace stripped. This option does not work together with the option. -z --zend-extension Load Zend extension. If only a filename is given, PHP tries to load this extension from the current default library path on your system (usually /etc/ld.so.conf on Linux systems, for example). Passing a filename with an absolute path will not use the system's library search path. A relative filename including directory information will tell PHP to try loading the extension relative to the current directory. --ini Show configuration file names and scanned directories. Available as of PHP 5.2.3. <literal>--ini</literal> example --rf --rfunction Show information about the given function or class method (e.g. number and name of the parameters). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support. basic <literal>--rf</literal> usage public function var_dump ] { - Parameters [2] { Parameter #0 [ $var ] Parameter #1 [ $... ] } } ]]> --rc --rclass Show information about the given class (list of constants, properties and methods). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support. <literal>--rc</literal> example class Directory ] { - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [0] { } - Methods [3] { Method [ public method close ] { } Method [ public method rewind ] { } Method [ public method read ] { } } } ]]> --re --rextension Show information about the given extension (list of &php.ini; options, defined functions, constants and classes). Available as of PHP 5.1.2. This option is only available if PHP was compiled with Reflection support. <literal>--re</literal> example extension #19 json version 1.2.1 ] { - Functions { Function [ function json_encode ] { } Function [ function json_decode ] { } } } ]]> --rz --rzendextension Show the configuration information for the given Zend extension (the same information that is returned by phpinfo). Available as of PHP 5.4.0. --ri --rextinfo Show the configuration information for the given extension (the same information that is returned by phpinfo). Available as of PHP 5.2.2. The core configuration information is available using "main" as extension name. <literal>--ri</literal> example enabled "Olson" Timezone Database Version => 2009.20 Timezone Database => internal Default timezone => Europe/Oslo Directive => Local Value => Master Value date.timezone => Europe/Oslo => Europe/Oslo date.default_latitude => 59.930972 => 59.930972 date.default_longitude => 10.776699 => 10.776699 date.sunset_zenith => 90.583333 => 90.583333 date.sunrise_zenith => 90.583333 => 90.583333 ]]>
Options -rBRFEH, --ini and --r[fcezi] are available only in &cli;.
Executing PHP files Usage There are three different ways of supplying the &cli.sapi; with PHP code to be executed: Tell PHP to execute a certain file. Both ways (whether using the switch or not) execute the file my_script.php. Note that there is no restriction on which files can be executed; in particular, the filename is not required have a .php extension. If arguments need to be passed to the script when using , the first argument must be --. Pass the PHP code to execute directly on the command line. Special care has to be taken with regard to shell variable substitution and usage of quotes. Read the example carefully: there are no beginning or ending tags! The switch simply does not need them, and using them will lead to a parse error. Provide the PHP code to execute via standard input (stdin). This gives the powerful ability to create PHP code dynamically and feed it to the binary, as shown in this (fictional) example: final_output.txt ]]> You cannot combine any of the three ways to execute code. As with every shell application, the PHP binary accepts a number of arguments; however, the PHP script can also receive further arguments. The number of arguments that can be passed to your script is not limited by PHP (and although the shell has a limit to the number of characters which can be passed, this is not in general likely to be hit). The arguments passed to the script are available in the global array $argv. The first index (zero) always contains the name of the script as called from the command line. Note that, if the code is executed in-line using the command line switch , the value of $argv[0] will be just a dash (-). The same is true if the code is executed via a pipe from STDIN. A second global variable, $argc, contains the number of elements in the $argv array (not the number of arguments passed to the script). As long as the arguments to be passed to the script do not start with the - character, there's nothing special to watch out for. Passing an argument to the script which starts with a - will cause trouble because the PHP interpreter thinks it has to handle it itself, even before executing the script. To prevent this, use the argument list separator --. After this separator has been parsed by PHP, every following argument is passed untouched to the script. [args...] [...] # This will pass the '-h' argument to the script and prevent PHP from showing its usage $ php -r 'var_dump($argv);' -- -h array(2) { [0]=> string(1) "-" [1]=> string(2) "-h" } ]]> However, on Unix systems there's another way of using PHP for shell scripting: make the first line of the script start with #!/usr/bin/php (or whatever the path to your PHP &cli; binary is if different). The rest of the file should contain normal PHP code within the usual PHP starting and end tags. Once the execution attributes of the file are set appropriately (e.g. chmod +x test), the script can be executed like any other shell or perl script: Execute PHP script as shell script ]]> Assuming this file is named test in the current directory, it is now possible to do the following: string(6) "./test" [1]=> string(2) "-h" [2]=> string(2) "--" [3]=> string(3) "foo" } ]]> As can be seen, in this case no special care needs to be taken when passing parameters starting with -. The PHP executable can be used to run PHP scripts absolutely independent of the web server. On Unix systems, the special #! (or "shebang") first line should be added to PHP scripts so that the system can automatically tell which program should run the script. On Windows platforms, it's possible to associate php.exe with the double click option of the .php extension, or a batch file can be created to run scripts through PHP. The special shebang first line for Unix does no harm on Windows (as it's formatted as a PHP comment), so cross platform programs can be written by including it. A simple example of writing a command line PHP program is shown below. Script intended to be run from command line (script.php) This is a command line PHP script with one option. Usage: The script above includes the Unix shebang first line to indicate that this file should be run by PHP. We are working with a &cli; version here, so no HTTP headers will be output. The program first checks that there is the required one argument (in addition to the script name, which is also counted). If not, or if the argument was , , or , the help message is printed out, using $argv[0] to dynamically print the script name as typed on the command line. Otherwise, the argument is echoed out exactly as received. To run the above script on Unix, it must be made executable, and called simply as script.php echothis or script.php -h. On Windows, a batch file similar to the following can be created for this task: Batch file to run a command line PHP script (script.bat) Assuming the above program is named script.php, and the &cli; php.exe is in C:\php\php.exe, this batch file will run it, passing on all appended options: script.bat echothis or script.bat -h. See also the Readline extension documentation for more functions which can be used to enhance command line applications in PHP. On Windows, PHP can be configured to run without the need to supply the C:\php\php.exe or the .php extension, as described in Command Line PHP on Microsoft Windows.
Input/output streams I/O streams The &cli.sapi; defines a few constants for I/O streams to make programming for the command line a bit easier. CLI specific Constants Constant Description STDIN An already opened stream to stdin. This saves opening it with ]]> If you want to read single line from stdin, you can use ]]> STDOUT An already opened stream to stdout. This saves opening it with ]]> STDERR An already opened stream to stderr. This saves opening it with ]]>
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: You do not need to explicitly close these streams, as they are closed automatically by PHP when your script ends. These constants are not available if reading the PHP script from stdin.
Interactive shell As of PHP 5.1.0, the &cli.sapi; provides an interactive shell using the option if PHP is compiled with the option. As of PHP 7.1.0 the interactive shell is also available on Windows, if the readline extension is enabled. Using the interactive shell you are able to type PHP code and have it executed directly. Executing code using the interactive shell echo 5+8; 13 php > function addTwo($n) php > { php { return $n + 2; php { } php > var_dump(addtwo(2)); int(4) php > ]]> The interactive shell also features tab completion for functions, constants, class names, variables, static method calls and class constants. Tab completion Pressing the tab key twice when there are multiple possible completions will result in a list of these completions: strp[TAB][TAB] strpbrk strpos strptime php > strp ]]> When there is only one possible completion, pressing tab once will complete the rest on the same line: strpt[TAB]ime( ]]> Completion will also work for names that have been defined during the current interactive shell session: $fooThisIsAReallyLongVariableName = 42; php > $foo[TAB]ThisIsAReallyLongVariableName ]]> The interactive shell stores your history which can be accessed using the up and down keys. The history is saved in the ~/.php_history file. As of PHP 5.4.0, the &cli.sapi; provides the &php.ini; settings cli.pager and cli.prompt. The cli.pager setting allows an external program (such as less) to act as a pager for the output instead of being displayed directly on the screen. The cli.prompt setting makes it possible to change the php > prompt. In PHP 5.4.0 it was also made possible to set &php.ini; settings in the interactive shell using a shorthand notation. Setting &php.ini; settings in the interactive shell The cli.prompt setting: #cli.prompt=hello world :> hello world :> ]]> Using backticks it is possible to have PHP code executed in the prompt: #cli.prompt=`echo date('H:i:s');` php > 15:49:35 php > echo 'hi'; hi 15:49:43 php > sleep(2); 15:49:45 php > ]]> Setting the pager to less: #cli.pager=less php > phpinfo(); (output displayed in less) php > ]]> The cli.prompt setting supports a few escape sequences: <parameter>cli.prompt</parameter> escape sequences Sequence Description \e Used for adding colors to the prompt. An example could be \e[032m\v \e[031m\b \e[34m\> \e[0m \v The PHP version. \b Indicates which block PHP is in. For instance /* to indicate being inside a multi-line comment. The outer scope is denoted by php. \> Indicates the prompt character. By default this is >, but changes when the shell is inside an unterminated block or string. Possible characters are: ' " { ( >
Files included through auto_prepend_file and auto_append_file are parsed in this mode but with some restrictions - e.g. functions have to be defined before called. Autoloading is not available if using PHP in &cli; interactive mode.
Built-in web server This web server was designed to aid application development. It may also be useful for testing purposes or for application demonstrations that are run in controlled environments. It is not intended to be a full-featured web server. It should not be used on a public network. As of PHP 5.4.0, the &cli.sapi; provides a built-in web server. The web server runs only one single-threaded process, so PHP applications will stall if a request is blocked. URI requests are served from the current working directory where PHP was started, unless the -t option is used to specify an explicit document root. If a URI request does not specify a file, then either index.php or index.html in the given directory are returned. If neither file exists, the lookup for index.php and index.html will be continued in the parent directory and so on until one is found or the document root has been reached. If an index.php or index.html is found, it is returned and $_SERVER['PATH_INFO'] is set to the trailing part of the URI. Otherwise a 404 response code is returned. If a PHP file is given on the command line when the web server is started it is treated as a "router" script. The script is run at the start of each HTTP request. If this script returns &false;, then the requested resource is returned as-is. Otherwise the script's output is returned to the browser. Standard MIME types are returned for files with extensions: .3gp, .apk, .avi, .bmp, .css, .csv, .doc, .docx, .flac, .gif, .gz, .gzip, .htm, .html, .ics, .jpe, .jpeg, .jpg, .js, .kml, .kmz, .m4a, .mov, .mp3, .mp4, .mpeg, .mpg, .odp, .ods, .odt, .oga, .ogg, .ogv, .pdf, .pdf, .png, .pps, .pptx, .qt, .svg, .swf, .tar, .text, .tif, .txt, .wav, .webm, .wmv, .xls, .xlsx, .xml, .xsl, .xsd, and .zip. Changelog: Supported MIME Types (file extensions) &Version; &Description; 5.5.12 .xml, .xsl, and .xsd 5.5.7 .3gp, .apk, .avi, .bmp, .csv, .doc, .docx, .flac, .gz, .gzip, .ics, .kml, .kmz, .m4a, .mp3, .mp4, .mpg, .mpeg, .mov, .odp, .ods, .odt, .oga, .pdf, .pptx, .pps, .qt, .swf, .tar, .text, .tif, .wav, .wmv, .xls, .xlsx, and .zip 5.5.5 .pdf 5.4.11 .ogg, .ogv, and .webm 5.4.4 .htm and .svg
Starting the web server The terminal will show: After URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to: Starting with a specific document root directory The terminal will show: Using a Router Script In this example, requests for images will display them, but requests for HTML files will display "Welcome to PHP": Welcome to PHP

"; } ?>]]>
Checking for CLI Web Server Use To reuse a framework router script during development with the CLI web server and later also with a production web server: ]]> Handling Unsupported File Types If you need to serve a static resource whose MIME type is not handled by the CLI web server, use: ]]> Accessing the CLI Web Server From Remote Machines You can make the web server accessible on port 8000 to any interface with:
INI settings CLI SAPI Configuration Options &Name; &Default; &Changeable; &Changelog; cli_server.color "0" PHP_INI_ALL Available since PHP 5.4.0.
&ini.descriptions.title; cli_server.color boolean Enable the built-in development web server to use ANSI color coding in terminal output.