Using PHP from the command line
The main focus of Sapi is for developing shell applications with PHP. There are quite a few differences between the 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.
Introduction
The main focus of Sapi is for developing shell applications with PHP. There are quite a few differences between the 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 Sapi is enabled by default using --enable-cli, but may be disabled using the --disable-cli 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 --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.
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 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 --enable-cli-win32. This does the same as the Cli version, except that it doesn't output anything and thus provides no console.
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 SAPIs
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 Sapi.
Cli is started up in quiet mode by default, though the
-qand--no-headerswitches 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. (
-Cand--no-chdirswitches kept for compatibility)Plain text error messages (no HTML formatting).
There are certain Ini directives which are overridden by the Sapi because they do not make sense in shell environments:
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 environment 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 $argcand$argvare automatically set to the appropriate values when using the Cli SAPI. These values can also be found in the$_SERVERarray, for example:$_SERVER['argv'].The presence of$argvor$_SERVER['argv']is not a reliable indication that a script is being run from the command line because they may be set in other contexts when register_argc_argv is enabled. The value returned byphp_sapi_name()should be checked instead. <?php if (php_sapi_name() === 'cli') { echo "This is being run from the command line!\n"; } Feature-8-5-0output_buffering false Although the 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. NoteThese directives cannot be initialized with another value from the configuration file 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).
NoteIt 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 Sapi does not change the current directory to the directory of the executed script.
Example showing the difference to the CGI SAPI:
php<?php // Our simple test application named test.php echo getcwd(), "\n"; ?>When using the CGI version, the output is:
output$ pwd /tmp $ php -q another_directory/test.php /tmp/another_directoryThis clearly shows that PHP changes its current directory to the one of the executed script.
Using the Sapi yields:
output$ pwd /tmp $ php -f another_directory/test.php /tmpThis allows greater flexibility when writing shell tools in PHP.
NoteThe CGI SAPI supports this Sapi behaviour by means of the
-Cswitch when run from the command line.
Command line options
The list of command line options provided by the PHP binary can be queried at any time 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 <addr>:<port> Run with built-in web server.
-t <docroot> Specify document root <docroot> for built-in web server.
-s Output HTML syntax highlighted source.
-v Version number
-w Output source with stripped comments and whitespace.
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>.
--rz <name> Show information about Zend extension <name>.
--ri <name> Show configuration for extension <name>.| 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 Ini, or a custom INI file (which does not need to be named Ini), e.g.:$ php -c /custom/directory/ my_script.php $ php -c /custom/directory/custom-file.ini my_script.phpIf this option is not specified, Ini is searched for in the default locations. |
| -n | --no-php-ini | Ignore Ini completely. |
| -d | --define | Set a custom value for any of the configuration directives allowed in Ini. The syntax is: -d configuration_directive[=value]Example of using -d to set an INI setting# Omitting the value part will set the given configuration directive to "1" $ php -d max_execution_time -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(1) "1" # Passing an empty value part will set the configuration directive to "" php -d max_execution_time= -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(0) "" # The configuration directive will be set to anything passed after the '=' character $ php -d max_execution_time=20 -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(2) "20" $ php -d max_execution_time=doesntmakesense -r '$foo = ini_get("max_execution_time"); var_dump($foo);' string(15) "doesntmakesense" |
| -e | --profile-info | Activate the extended information mode, to be used by a debugger/profiler. |
| -f | --file | Parse and execute the specified file. The -f is optional and may be omitted - providing just the filename to execute is sufficient. |
| -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 | Syntax check but do not execute the given PHP code. The input from standard input will be processed if no filenames are specified, otherwise each filename will be checked. On success, the text No syntax errors detected in <filename> is written to standard output. On failure, the text Errors parsing <filename> is written to standard output in addition to the internal parser error. If any failures are found in the specified files (or standard input), the shell return code is set to -1, otherwise the shell return code is set to 0.This option won't find fatal errors (like undefined functions) that require executing the code.Prior to PHP 8.3.0, it was only possible to specify one filename to be checked.This option does not work together with the -r option. |
| -m | --modules | Printing built in (and loaded) PHP and Zend modules$ php -m [PHP Modules] xml tokenizer standard session posix pcre overload mysql mbstring ctype [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$ php -r "$foo = get_defined_constants();" PHP Parse error: syntax error, unexpected '=' in Command line code on line 1 Parse error: syntax error, unexpected '=' in Command line code on line 1The 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:$ php -r " = get_defined_constants();"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$ php -r '$foo = get_defined_constants(); var_dump($foo);' array(370) { ["E_ERROR"]=> 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 Bugs. It is still easy to run into trouble when trying to use variables (shell or PHP) in command-line code, or using backslashes for escaping, so take great care when doing so. You have been warned!-r is available in the 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. |
| -R | --process-code | PHP code to execute for every input line.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. |
| -E | --process-end | PHP code to execute after processing the input.Using the -B, -R and -E options to count the number of lines of a project.$ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";' Total Lines: 37328 |
| -S | --server | Starts built-in web server. |
| -t | --docroot | Specifies document root for built-in web server. |
| -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 -r option. |
| -v | --version | Using -v to get the SAPI name and the version of PHP and Zend$ php -v PHP 5.3.1 (cli) (built: Dec 11 2009 19:55:07) Copyright (c) 1997-2009 The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2009 Zend Technologies |
| -w | --strip | Display source with comments and whitespace stripped.This option does not work together with the -r option. |
| --ini | Show configuration file names and scanned directories. Optionally, pass --ini=diff to show the differences between the loaded configuration files and the default configuration. --ini example$ php --ini Configuration File (php.ini) Path: /usr/dev/php/5.2/lib Loaded Configuration File: /usr/dev/php/5.2/lib/php.ini Scan for additional .ini files in: (none) Additional .ini files parsed: (none) The --ini=diff option is not available prior to PHP 8.5.0. | |
| --rf | --rfunction | Show information about the given function or class method (e.g. number and name of the parameters).This option is only available if PHP was compiled with Reflection support.basic --rf usage$ php --rf var_dump Function [ <internal> public function var_dump ] { - Parameters [2] { Parameter #0 [ <required> $var ] Parameter #1 [ <optional> $... ] } } |
| --rc | --rclass | Show information about the given class (list of constants, properties and methods).This option is only available if PHP was compiled with Reflection support.--rc example$ php --rc Directory Class [ <internal:standard> class Directory ] { - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [0] { } - Methods [3] { Method [ <internal> public method close ] { } Method [ <internal> public method rewind ] { } Method [ <internal> public method read ] { } } } |
| --re | --rextension | Show information about the given extension (list of Ini options, defined functions, constants and classes).This option is only available if PHP was compiled with Reflection support.--re example$ php --re json Extension [ <persistent> extension #19 json version 1.2.1 ] { - Functions { Function [ <internal> function json_encode ] { } Function [ <internal> function json_decode ] { } } } |
| --rz | --rzendextension | Show the configuration information for the given Zend extension (the same information that is returned by phpinfo()). |
| --ri | --rextinfo | Show the configuration information for the given extension (the same information that is returned by phpinfo()). The core configuration information is available using "main" as extension name.--ri example$ php --ri date date date/time support => 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
There are three different ways of supplying the Sapi with PHP code to be executed:
Tell PHP to execute a certain file.
output$ php my_script.php $ php -f my_script.phpBoth ways (whether using the
-fswitch or not) execute the filemy_script.php. Note that there is no restriction on which files can be executed; in particular, the filename is not required have a.phpextension.Pass the PHP code to execute directly on the command line.
output$ php -r 'print_r(get_defined_constants());'Special care has to be taken with regard to shell variable substitution and usage of quotes.
NoteRead the example carefully: there are no beginning or ending tags! The
-rswitch 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:
output$ some_application | some_filter | php | sort -u > 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 -r, the value of $argv[0] will be "Standard input code"; prior to PHP 7.2.0, it was a dash ("-") instead. 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.
# This will not execute the given code but will show the PHP usage
$ php -r 'var_dump($argv);' -h
Usage: php [options] [-f] <file> [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
#!/usr/bin/php
<?php
var_dump($argv);
?>Assuming this file is named test in the current directory, it is now possible to do the following:
$ chmod +x test
$ ./test -h -- foo
array(4) {
[0]=>
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)
#!/usr/bin/php
<?php
if ($argc != 2 || in_array($argv[1], array('--help', '-help', '-h', '-?'))) {
?>
This is a command line PHP script with one option.
Usage:
<?php echo $argv[0]; ?> <option>
<option> can be some word you would like
to print out. With the --help, -help, -h,
or -? options, you can get this help.
<?php
} else {
echo $argv[1];
}
?>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 --help, -help, -h 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)
@echo OFF
"C:\php\php.exe" script.php %*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.
On Windows it is recommended to run PHP under an actual user account. When running under a network service certain operations will fail, because "No mapping between account names and security IDs was done".
Input/output streams
The Sapi defines a few constants for I/O streams to make programming for the command line a bit easier.
| 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.
These constants are not available if reading the PHP script from stdin.
Interactive shell
The Sapi provides an interactive shell using the -a option if PHP is compiled with the --with-readline 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
$ php -a
Interactive shell
php > 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:
php > strp[TAB][TAB]
strpbrk strpos strptime
php > strpWhen there is only one possible completion, pressing tab once will complete the rest on the same line:
php > strpt[TAB]ime(Completion will also work for names that have been defined during the current interactive shell session:
php > $fooThisIsAReallyLongVariableName = 42;
php > $foo[TAB]ThisIsAReallyLongVariableNameThe 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 8.4.0, the path to the history file can be set using the PHP_HISTFILE environment variable.
The Sapi provides the 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.
It is also possible to set Ini settings in the interactive shell using a shorthand notation.
Setting Ini settings in the interactive shell
The cli.prompt setting:
php > #cli.prompt=hello world :>
hello world :> Using backticks it is possible to have PHP code executed in the prompt:
php > #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:
php > #cli.pager=less
php > phpinfo();
(output displayed in less)
php > The cli.prompt setting supports a few 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.
Interactive mode
If the readline extension is not available, prior to PHP 8.1.0, invoking the Sapi with the -a option provided the interactive mode. In this mode, a complete PHP script is supposed to be given via STDIN, and after termination with CTRLD (POSIX) or CTRLZ followed by ENTER (Windows), this script is evaluated. This is basically the same as invoking the Sapi without the -a option.
As of PHP 8.1.0, invoking the Sapi with the -a option fails, if the readline extension is not available.
Built-in web server
This web server is 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.
The 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.
As of PHP 8.4.0, this index file lookup is performed even when the requested path looks like a file, i.e. its last path component contains a period, but cannot be located. Previously, such requests skipped the lookup and immediately returned a 404 response.
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.png.pps.pptx.qt.svg.swf.tar.text.tif.txt.wav.webm.wmv.xls.xlsx.xml.xsl.xsd.zip
.
As of PHP 7.4.0, the built-in webserver can be configured to fork multiple workers in order to test code that requires multiple concurrent requests to the built-in webserver. Set the PHP_CLI_SERVER_WORKERS environment variable to the number of desired workers before starting the server.
Multiple workers are not supported on Windows.
For information on PHP commandline usage and options, run php --help or man php. Not all options will apply when running the web server.
This experimental feature is not intended for production usage. Generally, the built-in Web Server is not intended for production usage.
Starting the web server
$ cd ~/public_html
$ php -S localhost:8000The terminal will show:
PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quitAfter URI requests for http://localhost:8000/ and http://localhost:8000/myscript.html the terminal will show something similar to:
PHP 5.4.0 Development Server started at Thu Jul 21 10:43:28 2011
Listening on localhost:8000
Document root is /home/me/public_html
Press Ctrl-C to quit.
[Thu Jul 21 10:48:48 2011] ::1:39144 GET /favicon.ico - Request read
[Thu Jul 21 10:48:50 2011] ::1:39146 GET / - Request read
[Thu Jul 21 10:48:50 2011] ::1:39147 GET /favicon.ico - Request read
[Thu Jul 21 10:48:52 2011] ::1:39148 GET /myscript.html - Request read
[Thu Jul 21 10:48:52 2011] ::1:39149 GET /favicon.ico - Request readNote that prior to PHP 7.4.0, symlinked statical resources have not been accessible on Windows, unless the router script would handle these.
Starting with a specific document root directory
$ cd ~/public_html
$ php -S localhost:8000 -t foo/The terminal will show:
PHP 5.4.0 Development Server started at Thu Jul 21 10:50:26 2011
Listening on localhost:8000
Document root is /home/me/public_html/foo
Press Ctrl-C to quitUsing a Router Script
In this example, requests for images will display them, but requests for HTML files will display "Welcome to PHP":
<?php
// router.php
if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"])) {
return false; // serve the requested resource as-is.
} else {
echo "<p>Welcome to PHP</p>";
}
?>$ php -S localhost:8000 router.phpChecking 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:
<?php
// router.php
if (php_sapi_name() == 'cli-server') {
/* route static assets and return false */
}
/* go on with normal index.php operations */
?>$ php -S localhost:8000 router.phpHandling Unsupported File Types
If you need to serve a static resource whose MIME type is not handled by the CLI web server, use:
<?php
// router.php
$path = pathinfo($_SERVER["SCRIPT_FILENAME"]);
if ($path["extension"] == "el") {
header("Content-Type: text/x-script.elisp");
readfile($_SERVER["SCRIPT_FILENAME"]);
}
else {
return FALSE;
}
?>$ php -S localhost:8000 router.phpAccessing the CLI Web Server From Remote Machines
You can make the web server accessible on port 8000 to any interface with:
$ php -S 0.0.0.0:8000The built-in Web Server should not be used on a public network.
INI settings
| Name | Default | Changeable | Changelog |
|---|---|---|---|
| cli_server.color | "0" | INI_ALL |
Title
cli_server.colorboolEnable the built-in development web server to use ANSI color coding in terminal output.