• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • PHP 的命令行模式

    从版本 4.3.0 开始,PHP 提供了一种新类型的 CLI SAPI(Server Application Programming Interface,服务端应用编程端口)支持,名为 CLI,意为Command Line Interface,即命令行接口。顾名思义,该 CLI SAPI 模块主要用作 PHP 的开发外壳应用。CLI SAPI和其它 CLI SAPI 模块相比有很多的不同之处,我们将在本章中详细阐述。值得一提的是,CLI 和CGI是不同的 SAPI,尽管它们之间有很多共同的行为。

    CLI SAPI最先是随 PHP 4.2.0 版本发布的,但仍旧只是一个实验性的版本,并需要在运行 ./configure 时加上 --enable-cli 参数。从 PHP 4.3.0 版本开始,CLI SAPI成为了正式模块,--enable-cli 参数会被默认得设置为 on,也可以用参数 --disable-cli 来屏蔽。

    从 PHP 4.3.0开始,CLI/CGI 二进制执行文件的文件名、位置和是否存在会根据 PHP 在系统上的安装而不同。在默认情况下,当运行 make 时,CGI 和 CLI 都会被编译并且分别放置在 PHP 源文件目录的sapi/cgi/phpsapi/cli/php下。可以注意到两个文件都被命名为了 php。在 make install 的过程中会发生什么取决于配置行。如果在配置的时候选择了一个 SAPI 模块,如 apxs,或者使用了 --disable-cgi 参数,则在 make install 的过程中,CLI 将被拷贝到{PREFIX}/bin/php,除非 CGI 已经被放置在了那个位置。因此,例如,如果在配置行中有 --with--apxs,则在make install的过程中,CLI 将被拷贝到{PREFIX}/bin/php。如果希望撤销 CGI 执行文件的安装,请在 make install 之后运行 make install-cli。或者,也可以在配置行中加上 --disable-cgi 参数。

    Note:

    由于 --enable-cli--enable-cgi 同时默认有效,因此,不必再配置行中加上 --enable-cli 来使得 CLI 在 make install 过程中被拷贝到{PREFIX}/bin/php

    在 PHP 4.2.0 到 PHP 4.2.3 之间的 Windows 发行包中,CLI 的文件名为php-cli.exe,相同文件夹下的php.exe为 CGI。从 PHP 4.3.0 版本开始,Windows 的发行包中 CLI 的执行文件为php.exe,被放置在一个单独的名为cli的文件夹下,即cli/php.exe。在 PHP 5 中,CLI 存在于主文件夹中,名为php.exe,而 CGI 版本名为php-cgi.exe

    从 PHP 5 起,一个名为php-win.exe的新文件随包发布。它相当于 CLI 版本,但是 php-win 不输出任何内容,便不提供控制台(不会弹出“DOS 窗口”)。这种方式类似于 php-gtk。需要使用 --enable-cli-win32 选项来配置它。

    Note: 如何得知自己使用的是哪个 SAPI?

    在命令行下,运行 php -v 便能得知该php是 CGI 还是 CLI。请参考函数 php_sapi_name() 以及常量 PHP_SAPI

    Note:

    在 PHP 4.3.2 中加入了 Unix 的man页面。可以在命令行中键入 man php 来查看。

    以下为CLI SAPI和其它 CLI SAPI 模块相比的显著区别:

    • CGI SAPI不同,其输出没有任何头信息。

      尽管CGI SAPI提供了取消 HTTP 头信息的方法,但在CLI SAPI中并不存在类似的方法以开启 HTTP 头信息的输出。

      CLI 默认以安静模式开始,但为了保证兼容性,-q--no-header 参数为了向后兼容仍然保留,使得可以使用旧的 CGI 脚本。

      在运行时,不会把工作目录改为脚本的当前目录(可以使用 -C--no-chdir 参数来兼容 CGI 模式)。

      出错时输出纯文本的错误信息(非 HTML 格式)。

    • CLI SAPI强制覆盖了php.ini中的某些设置,因为这些设置在外壳环境下是没有意义的。

      覆盖php.ini设置选项
      设置选项CLI SAPI默认值备注
      html_errorsFALSE 无意义的 HTML 标记符会使得出错信息很凌乱,所以在外壳下阅读报错信息是十分困难的。因此将该选项的默认值改为 FALSE
      implicit_flushTRUE 在命令行模式下,所有来自 print 和 echo 的输出将被立即写到输出端,而不作任何地缓冲操作。如果希望延缓或控制标准输出,仍然可以使用 output buffering 设置项。
      max_execution_time0(无限值) 鉴于在外壳环境下使用 PHP 的无穷的可能性,最大运行时间被设置为了无限值。为 web 开发的应用程序可能只需运行几秒钟时间,而外壳应用程序的运行时间可能会长的多。
      register_argc_argvTRUE

      由于该设置为 TRUE,将总是可以在CLI SAPI中访问到argc(传送给应用程序参数的个数)和argv(包含有实际参数的数组)。

      对于 PHP 4.3.0,在使用CLI SAPI时,PHP 变量$argc$argv已被注册并且设定了对应的值。而在这之前的版本,这两个变量在CGI或者模块版本中的建立依赖于将 PHP 的设置选项 register_globals 设为on。除了版本和register_globals设定以外,可以随时通过调用 $_SERVER 或者$HTTP_SERVER_VARS来访问它们。例如:$_SERVER['argv']

      Note:

      这些设置无法在设置文件php.ini或任何指定的其它文件中被初始化为其它值。这些默认值被限制在所有其它的设置文件被解析后改变。不过,它们的值可以在程序运行的过程中被改变(尽管对于该运行过程来说,这些设置项是没有意义的)。

    • 为了减轻外壳环境下的工作,我们定义了如下常量:

      CLI 专用常量
      常量名称描 述
      STDIN 一个已打开的指向stdin的流。可以用如下方法来调用:
      <?php
      $stdin = fopen('php://stdin', 'r');
      ?>
      
      如果想从stdin读取一行内容,可以使用
      <?php
      $line = trim(fgets(STDIN)); // 从 STDIN 读取一行
      fscanf(STDIN, "%d\n", $number); // 从 STDIN 读取数字
      ?>
      
      STDOUT 一个已打开的指向stdout的流。可以用如下方式来调用:
      <?php
      $stdout = fopen('php://stdout', 'w');
      ?>
      
      STDERR 一个已打开的指向stderr的流。可以用如下方式来调用:
      <?php
      $stderr = fopen('php://stderr', 'w');
      ?>
      

      有了以上常量,就无需自己建立指向诸如stderr的流,只需简单的使用这些常量来代替流指向:

      php -r 'fwrite(STDERR, "stderr\n");'
      无需自己来关闭这些流,PHP 会自动完成这些操作。

    • CLI SAPI不会将当前目录改为已运行的脚本所在的目录。

      以下范例显示了本模块与CGI SAPI模块之间的不同:

      <?php
      // 名为 test.php 的简单测试程序
      echo getcwd(), "\n";
      ?>
      

      在使用CGI版本时,其输出为

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

      明显可以看到 PHP 将当前目录改成了刚刚运行过的脚本所在的目录。

      使用CLI SAPI模式,得到:

      $ pwd
      /tmp
      $ php -q another_directory/test.php
      /tmp
      
      这使得在利用 PHP 编写外壳工具时获得了很大的便利。

      Note:

      可以在命令行运行时给该CGI SAPI加上 -C 参数,使其支持CLI SAPI的功能。

    以下是 PHP 二进制文件(即php.exe程序)提供的命令行模式的选项参数,随时可以运行带 -h 参数的 PHP 命令来查询这些参数。

    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 <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
    

    CLI SAPI模块有以下三种不同的方法来获取要运行的 PHP 代码:

    1. 让 PHP 运行指定文件。

      php my_script.php
      php -f my_script.php
      

      以上两种方法(使用或不使用 -f 参数)都能够运行给定的my_script.php文件。可以选择任何文件来运行,指定的 PHP 脚本并非必须要以.php为扩展名,它们可以有任意的文件名和扩展名。

    2. 在命令行直接运行 PHP 代码。

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

      在使用这种方法时,请注意外壳变量的替代及引号的使用。

      Note:

      请仔细阅读以上范例,在运行代码时没有开始和结束的标记符!加上 -r 参数后,这些标记符是不需要的,加上它们会导致语法错误。

    3. 通过标准输入(stdin)提供需要运行的 PHP 代码。

      以上用法提供了非常强大的功能,使得可以如下范例所示,动态地生成 PHP 代码并通过命令行运行这些代码:

      $ some_application | some_filter | php | sort -u >final_output.txt
      

    以上三种运行代码的方法不能同时使用。

    和所有的外壳应用程序一样,PHP 的二进制文件(php.exe文件)及其运行的 PHP 脚本能够接受一系列的参数。PHP 没有限制传送给脚本程序的参数的个数(外壳程序对命令行的字符数有限制,但通常都不会超过该限制)。传递给脚本的参数可在全局变量$argv中获取。该数组中下标为零的成员为脚本的名称(当 PHP 代码来自标准输入获直接用 -r 参数以命令行方式运行时,该名称为“-”)。另外,全局变量$argc存有$argv数组中成员变量的个数(而非传送给脚本程序的参数的个数)。

    只要传送给脚本的参数不是以-符号开头,就无需过多的注意什么。向脚本传送以-开头的参数会导致错误,因为 PHP 会认为应该由它自身来处理这些参数。可以用参数列表分隔符--来解决这个问题。在 PHP 解析完参数后,该符号后所有的参数将会被原样传送给脚本程序。

    # 以下命令将不会运行 PHP 代码,而只显示 PHP 命令行模式的使用说明:
    $ php -r 'var_dump($argv);' -h
    Usage: php [options] [-f] <file> [args...]
    [...]
    # 以下命令将会把“-h”参数传送给脚本程序,PHP 不会显示命令行模式的使用说明:
    $ php -r 'var_dump($argv);' -- -h
    array(2) {
      [0]=>
      string(1) "-"
      [1]=>
      string(2) "-h"
    }
    

    除此之外,还有另一个方法将 PHP 用于外壳脚本。可以在写一个脚本,并在第一行以#!/usr/bin/php开头,在其后加上以 PHP 开始和结尾标记符包含的正常的 PHP 代码,然后为该文件设置正确的运行属性(例如:chmod +x test)。该方法可以使得该文件能够像外壳脚本或 PERL 脚本一样被直接执行。

    #!/usr/bin/php
    <?php
        var_dump($argv);
    ?>
    

    假设改文件名为test并被放置在当前目录下,可以做如下操作:

    $ chmod +x test
    $ ./test -h -- foo
    array(4) {
      [0]=>
      string(6) "./test"
      [1]=>
      string(2) "-h"
      [2]=>
      string(2) "--"
      [3]=>
      string(3) "foo"
    }
    

    正如所看到的,在向该脚本传送以-开头的参数时,脚本仍然能够正常运行。

    PHP 4.3.3 以来有效的长选项:

    命令行选项
    选项名称长名称说明
    -a--interactive

    交互式运行 PHP。如果编译 PHP 时加入了 Readline 扩展(Windows 下不可用),那将会得到一个很好的外壳,包括一个自动完成的功能(例如可以在键入变量名的时候,按下 TAB 键,PHP 会自动完成该变量名)以及命令历史记录,可以用上下键来访问。历史记录存在~/.php_history文件中。

    Note:

    通过 auto_prepend_file 和 auto_append_file 包含的文件在此模式下会被解析,但有些限制,例如函数必须在被调用之前定义。

    -c--php-ini

    用该参数,可以指定一个放置php.ini文件的目录,或者直接指定一个自定义的INI文件(其文件名可以不是php.ini),例如:

    $ php -c /custom/directory/ my_script.php
    $ php -c /custom/directory/custom-file.ini my_script.php
    
    如果不指定此选项,PHP 将在默认位置搜索文件。

    -n--no-php-ini

    完全忽略php.ini。此参数在 PHP 4.3.0 以后有效。

    -d--define

    用该参数可以自行设置任何可以在php.ini文件中设置的配置选项的值,其语法为:

    -d configuration_directive[=value]
    

    例子(因版面原因而折行显示):

    # 取值部分被省略,将会把配置选项设为 "1"
    $ php -d max_execution_time
            -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
    string(1) "1"
    # 取值部分为空白,将会把配置选项设为 ""
    php -d max_execution_time=
            -r '$foo = ini_get("max_execution_time"); var_dump($foo);'
    string(0) ""
    # 配置选项将被设置成为任何 '=' 字符之后的值
    $  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

    激活扩展信息模式,被用于调试/测试。

    -f--file

    解析并运行 -f 选项给定的文件名。该参数为可选参数,可以省略,仅指明需要运行的文件名即可。

    -h and -?--help and --usage 使用该参数,可以得到完整的命令行参数的列表及这些参数作用的简单描述。
    -i--info 该命令行参数会调用 phpinfo() 函数并显示出结果。如果 PHP 没有正常工作,建议执行 php -i 命令来查看在信息表格之前或者对应的地方是否有任何错误信息输出。请注意当使用 CGI 摸索时,输出的内容为HTML格式,因此输出的信息篇幅较大。
    -l--syntax-check

    该参数提供了对指定 PHP 代码进行语法检查的方便的方法。如果成功,则向标准输出写入No syntax errors detected in <filename>字符串,并且外壳返回值为0。如果失败,则输出Errors parsing <filename>以及内部解析器错误信息到标准输出,同时外壳返回值将别设置为255

    该参数将无法检查致命错误(如未定义函数),如果也希望检测致命错误,请使用 -f 参数。

    Note:

    该参数不能和 -r 一同使用。

    -m--modules

    使用该参数,PHP 将打印出内置以及已加载的 PHP 及 Zend 模块:

    $ php -m
    [PHP Modules]
    xml
    tokenizer
    standard
    session
    posix
    pcre
    overload
    mysql
    mbstring
    ctype
    [Zend Modules]
    

    -r--run

    使用该参数可以在命令行内运行单行 PHP 代码。无需加上 PHP 的起始和结束标识符(<?php?>),否则将会导致语法解析错误。

    Note:

    使用这种形式的 PHP 时,应注意避免和外壳环境进行的命令行参数替换相冲突。

    显示语法解析错误的范例 $ php -r "$foo = get_defined_constants();" Command line code(1) : Parse error - parse error, unexpected '=' 这里的问题在于即使使用了双引号",sh/bash 仍然实行了参数替换。由于$foo没有被定义,被替换后它所在的位置变成了空字符,因此在运行时,实际被 PHP 读取的代码为: $ php -r " = get_defined_constants();" 正确的方法是使用单引号'。在用单引号引用的字符串中,变量不会被 sh/bash 还原成其原值。 $ 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"]=> [...] 如果使用的外壳不是 sh/bash,可能会碰到更多问题。请将碰到的 Bug 向 » https://bugs.php.net/ 报告。注意,当试图将 shell 变量用到代码中或者使用反斜线时仍然很容易碰到问题。

    Note:

    -rCLISAPI 中有效,在CGISAPI 中无效。

    Note:

    此选项只用于非常基本的用途。因此一些配置指令(例如 auto_prepend_file 和 auto_append_file)在此模式下被忽略。

    -B--process-begin

    在处理 stdin 之前先执行 PHP 代码。PHP 5 新加。

    -R--process-code

    对每个输入行都执行 PHP 代码。PHP 5 新加。

    此模式下有两个特殊变量:$argn$argi$argn包含 PHP 当前处理的行内容,而$argi则包含该行号。

    -F--process-file

    对每个输入行都执行 PHP 文件。PHP 5 新加。

    -E--process-end

    在处理完输入后执行的 PHP 代码。PHP 5 新加。

    使用 -B-R-E 选项来计算一个项目总行数的例子。

    $ find my_proj | php -B '$l=0;' -R '$l += count(@file($argn));' -E 'echo "Total Lines: $l\n";'
    Total Lines: 37328
    

    -s--syntax-highlight and --syntax-highlight

    显示有语法高亮色彩的源代码。

    该参数使用内建机制来解析文件并为其生成一个HTML高亮版本并将结果写到标准输出。请注意该过程所做的只是生成了一个<code> [...] </code>HTML标记的块,并不包含任何的HTML头。

    Note:

    该选项不能和 -r 参数同时使用。

    -v--version

    将 PHP,PHP SAPI 和 Zend 的版本信息写入标准输出。例如:

    $ php -v
    PHP 4.3.0 (cli), Copyright (c) 1997-2002 The PHP Group
    Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies
    

    -w--strip

    显示除去了注释和多余空白的源代码。

    Note:

    该选项不能和 -r 参数同时使用。

    -z--zend-extension

    加载 Zend 扩展库。如果仅给定一个文件名,PHP 将试图从当前系统扩展库的默认路径(在 Linux 系统下,该路径通常由/etc/ld.so.conf指定)加载该扩展库。如果用一个绝对路径指定文件名,则不会使用系统的扩展库默认路径。如果用相对路径指定的文件名,则 PHP 仅试图在当前目录的相对目录加载扩展库。

    PHP 的命令行模式能使得 PHP 脚本能完全独立于 web 服务器单独运行。如果使用 Unix 系统,需要在 PHP 脚本的最前面加上一行特殊的代码,使得它能够被执行,这样系统就能知道用哪个程序去运行该脚本。在 Windows 平台下可以将php.exe.php文件的双击属性相关联,也可以编写一个批处理文件来用 PHP 执行脚本。为 Unix 系统增加的第一行代码不会影响该脚本在 Windows 下的运行,因此也可以用该方法编写跨平台的脚本程序。以下是一个简单的 PHP 命令行程序的范例。

    Example #1 试图以命令行方式运行的 PHP 脚本(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];
    }
    ?>
    

    在以上脚本中,用第一行特殊的代码来指明该文件应该由 PHP 来执行。在这里使用 CLI 的版本,因此不会有 HTTP 头信息输出。在用 PHP 编写命令行应用程序时,可以使用两个参数:$argc$argv。前面一个的值是比参数个数大 1 的整数(运行的脚本本身的名称也被当作一个参数)。第二个是包含有参数的数组,其第一个元素为脚本的名称,下标为数字 0($argv[0])。

    以上程序中检查了参数的个数是大于 1 个还是小于 1 个。此外如果参数是 --help-help-h-? 时,打印出帮助信息,并同时动态输出脚本的名称。如果还收到了其它参数,将其显示出来。

    如果希望在 Unix 下运行以上脚本,需要使其属性为可执行文件,然后简单的运行 script.php echothisscript.php -h。在 Windows 下,可以为此编写一个批处理文件:

    Example #2 运行 PHP 命令行脚本的批处理文件(script.bat)

    @C:\php\php.exe script.php %1 %2 %3 %

    假设将上述程序命名为script.php,且 CLI 版的php.exe文件放置在c:\php\cli\php.exe,该批处理文件会帮助将附加的参数传给脚本程序:script.bat echothisscript.bat -h

    请参阅 Readline 扩展模块的有关文档,以获取更多的函数的信息。这些函数可以帮助完善 PHP 命令行应用程序。

    You can easily parse command line arguments into the $_GET variable by using the parse_str() function.
    <?php
    parse_str(implode('&', array_slice($argv, 1)), $_GET);
    ?>
    It behaves exactly like you'd expect with cgi-php.
    $ php -f somefile.php a=1 b[]=2 b[]=3
    This will set $_GET['a'] to '1' and $_GET['b'] to array('2', '3').
    Even better, instead of putting that line in every file, take advantage of PHP's auto_prepend_file directive. Put that line in its own file and set the auto_prepend_file directive in your cli-specific php.ini like so:
    auto_prepend_file = "/etc/php/cli-php5.3/local.prepend.php"
    It will be automatically prepended to any PHP file run from the command line.
    If you want to be interactive with the user and accept user input, all you need to do is read from stdin. 
    <?php
    echo "Are you sure you want to do this? Type 'yes' to continue: ";
    $handle = fopen ("php://stdin","r");
    $line = fgets($handle);
    if(trim($line) != 'yes'){
      echo "ABORTING!\n";
      exit;
    }
    echo "\n";
    echo "Thank you, continuing...\n";
    ?>
    
    For those of you who want the old CGI behaviour that changes to the actual directory of the script use:
    chdir(dirname($_SERVER['argv'][0]));
    at the beginning of your scripts.
    Using CLI (on WIN at least), some INI paths are relative to the current working directory. For example, if your error_log = "php_errors.log", then php_errors.log will be created (or appended to if already exists) in whatever directory you happen to be in at the moment if you have write access there. Instead of having random error logs all over the place because of this behavior, you may want to set error_log to a full path, perhaps to the php.exe directory.
    Check directly without calling functions:
    <?php
    if (PHP_SAPI === 'cli')
    {
      // ...
    }
    ?>
    You can define a constant to use it elsewhere
    <?php
    define('ISCLI', PHP_SAPI === 'cli');
    ?>
    
    Just a note for people trying to use interactive mode from the commandline.
    The purpose of interactive mode is to parse code snippits without actually leaving php, and it works like this:
    [root@localhost php-4.3.4]# php -a
    Interactive mode enabled
    <?php echo "hi!"; ?>
    <note, here we would press CTRL-D to parse everything we've entered so far>
    hi!
    <?php exit(); ?>
    <ctrl-d here again>
    [root@localhost php-4.3.4]#
    I noticed this somehow got ommited from the docs, hope it helps someone!
    Just a variant of previous script to accept arguments with '=' also
    <?php
    function arguments($argv) {
      $_ARG = array();
      foreach ($argv as $arg) {
       if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
       } elseif(ereg('-([a-zA-Z0-9])',$arg,$reg)) {
          $_ARG[$reg[1]] = 'true';
        }
      
      }
     return $_ARG;
    }
    ?>
    $ php myscript.php --user=nobody --password=secret -p --access="host=127.0.0.1 port=456" 
    Array
    (
      [user] => nobody
      [password] => secret
      [p] => true
      [access] => host=127.0.0.1 port=456
    )
    I needed this, you proly wont tho.
    puts the exicution args into $_GET
    <?php
    if ($argv) {
      foreach ($argv as $k=>$v)
      {
        if ($k==0) continue;
        $it = explode("=",$argv[$i]);
        if (isset($it[1])) $_GET[$it[0]] = $it[1];
      }
    }
    ?>
    
    i use emacs in c-mode for editing. in 4.3, starting a cli script like so:
    #!/usr/bin/php -q /* -*- c -*- */
    <?php
    told emacs to drop into c-mode automatically when i loaded the file for editing. the '-q' flag didn't actually do anything (in the older cgi versions, it suppressed html output when the script was run) but it caused the commented mode line to be ignored by php.
    in 5.2, '-q' has apparently been deprecated. replace it with '--' to achieve the 4.3 invocation-with-emacs-mode-line behavior:
    #!/usr/bin/php -- /* -*- c -*- */
    <?php
    don't go back to your 4.3 system and replace '-q' with '--'; it seems to cause php to hang waiting on STDIN...
    Ok, I've had a heck of a time with PHP > 4.3.x and whether to use CLI vs CGI. The CGI version of 4.3.2 would return (in browser):
    ---
    No input file specified.
    ---
    And the CLI version would return:
    ---
    500 Internal Server Error
    ---
    It appears that in CGI mode, PHP looks at the environment variable PATH_TRANSLATED to determine the script to execute and ignores command line. That is why in the absensce of this environment variable, you get "No input file specified." However, in CLI mode the HTTP headers are not printed. I believe this is intended behavior for both situations but creates a problem when you have a CGI wrapper that sends environment variables but passes the actual script name on the command line.
    By modifying my CGI wrapper to create this PATH_TRANSLATED environment variable, it solved my problem, and I was able to run the CGI build of 4.3.2
    Parsing command line: optimization is evil!
    One thing all contributors on this page forgotten is that you can suround an argv with single or double quotes. So the join coupled together with the preg_match_all will always break that :)
    Here is a proposal:
    #!/usr/bin/php
    <?php
    print_r(arguments($argv));
    function arguments ( $args )
    {
     array_shift( $args );
     $endofoptions = false;
     $ret = array
      (
      'commands' => array(),
      'options' => array(),
      'flags'  => array(),
      'arguments' => array(),
      );
     while ( $arg = array_shift($args) )
     {
      // if we have reached end of options,
      //we cast all remaining argvs as arguments
      if ($endofoptions)
      {
       $ret['arguments'][] = $arg;
       continue;
      }
      // Is it a command? (prefixed with --)
      if ( substr( $arg, 0, 2 ) === '--' )
      {
       // is it the end of options flag?
       if (!isset ($arg[3]))
       {
        $endofoptions = true;; // end of options;
        continue;
       }
       $value = "";
       $com  = substr( $arg, 2 );
       // is it the syntax '--option=argument'?
       if (strpos($com,'='))
        list($com,$value) = split("=",$com,2);
       // is the option not followed by another option but by arguments
       elseif (strpos($args[0],'-') !== 0)
       {
        while (strpos($args[0],'-') !== 0)
         $value .= array_shift($args).' ';
        $value = rtrim($value,' ');
       }
       $ret['options'][$com] = !empty($value) ? $value : true;
       continue;
      }
      // Is it a flag or a serial of flags? (prefixed with -)
      if ( substr( $arg, 0, 1 ) === '-' )
      {
       for ($i = 1; isset($arg[$i]) ; $i++)
        $ret['flags'][] = $arg[$i];
       continue;
      }
      // finally, it is not option, nor flag, nor argument
      $ret['commands'][] = $arg;
      continue;
     }
     if (!count($ret['options']) && !count($ret['flags']))
     {
      $ret['arguments'] = array_merge($ret['commands'], $ret['arguments']);
      $ret['commands'] = array();
     }
    return $ret;
    }
    exit (0)
    /* vim: set expandtab tabstop=2 shiftwidth=2: */
    ?>
    
    You can also call the script from the command line after chmod'ing the file (ie: chmod 755 file.php).
    On your first line of the file, enter "#!/usr/bin/php" (or to wherever your php executable is located). If you want to suppress the PHP headers, use the line of "#!/usr/bin/php -q" for your path.
    If your php script doesn't run with shebang (#!/usr/bin/php),
    and it issues the beautifull and informative error message:
    "Command not found." just dos2unix yourscript.php
    et voila.
    If you still get the "Command not found." 
    Just try to run it as ./myscript.php , with the "./"
    if it works - it means your current directory is not in the executable search path.
    If your php script doesn't run with shebang (#/usr/bin/php),
    and it issues the beautifull and informative message:
    "Invalid null command." it's probably because the "!" is missing in the the shebang line (like what's above) or something else in that area.
    \Alon
    This posting is not a php-only problem, but hopefully will save someone a few hours of headaches. Running on MacOS (although this could happen on any *nix I suppose), I was unable to get the script to execute without specifically envoking php from the command line:
    [macg4:valencia/jobs] tim% test.php
    ./test.php: Command not found.
    However, it worked just fine when php was envoked on the command line:
    [macg4:valencia/jobs] tim% php test.php
    Well, here we are... Now what?
    Was file access mode set for executable? Yup.
    [macg4:valencia/jobs] tim% ls -l 
    total 16
    -rwxr-xr-x 1 tim staff  242 Feb 24 17:23 test.php
    And you did, of course, remember to add the php command as the first line of your script, yeah? Of course.
    #!/usr/bin/php
    <?php print "Well, here we are... Now what?\n"; ?>
    So why dudn't it work? Well, like I said... on a Mac.... but I also occasionally edit the files on my Windows portable (i.e. when I'm travelling and don't have my trusty Mac available)... Using, say, WordPad on Windows... and BBEdit on the Mac...
    Aaahhh... in BBEdit check how the file is being saved! Mac? Unix? or Dos? Bingo. It had been saved as Dos format. Change it to Unix:
    [macg4:valencia/jobs] tim% ./test.php
    Well, here we are... Now what?
    [macg4:valencia/jobs] tim% 
    NB: If you're editing your php files on multiple platforms (i.e. Windows and Linux), make sure you double check the files are saved in a Unix format... those \r's and \n's 'll bite cha!
    I had a problem with the $argv values getting split up when they contained plus (+) signs. Be sure to use the CLI version, not CGI to get around it.
    Monte
    Just another variant of previous script that group arguments doesn't starts with '-' or '--'
    <?php
    function arguments($argv) {
      $_ARG = array();
      foreach ($argv as $arg) {
       if (ereg('--([^=]+)=(.*)',$arg,$reg)) {
        $_ARG[$reg[1]] = $reg[2];
       } elseif(ereg('^-([a-zA-Z0-9])',$arg,$reg)) {
          $_ARG[$reg[1]] = 'true';
       } else {
          $_ARG['input'][]=$arg;
       }
      }
     return $_ARG;
    }
    print_r(arguments($argv));
    ?>
    $ php myscript.php --user=nobody /etc/apache2/*
    Array
    (
      [input] => Array
        (
          [0] => myscript.php
          [1] => /etc/apache2/apache2.conf
          [2] => /etc/apache2/conf.d
          [3] => /etc/apache2/envvars
          [4] => /etc/apache2/httpd.conf
          [5] => /etc/apache2/mods-available
          [6] => /etc/apache2/mods-enabled
          [7] => /etc/apache2/ports.conf
          [8] => /etc/apache2/sites-available
          [9] => /etc/apache2/sites-enabled
        )
      [user] => nobody
    )
    How to change current directory in PHP script to script's directory when running it from command line using PHP 4.3.0?
    (you'll probably need to add this to older scripts when running them under PHP 4.3.0 for backwards compatibility)
    Here's what I am using:
    chdir(preg_replace('/\\/[^\\/]+$/',"",$PHP_SELF));
    Note: documentation says that "PHP_SELF" is not available in command-line PHP scripts. Though, it IS available. Probably this will be changed in future version, so don't rely on this line of code...
    Use $_SERVER['PHP_SELF'] instead of just $PHP_SELF if you have register_globals=Off
    Parsing commandline argument GET String without changing the PHP script (linux shell):
    URL: index.php?a=1&b=2
    Result: output.html
    echo "" | php -R 'include("index.php");' -B 'parse_str($argv[1], $_GET);' 'a=1&b=2' >output.html
    (no need to change php.ini)
    You can put this 
     echo "" | php -R 'include("'$1'");' -B 'parse_str($argv[1], $_GET);' "$2"
    in a bash script "php_get" to use it like this:
     php_get index.php 'a=1&b=2' >output.html
    or directed to text browser...
     php_get index.php 'a=1&b=2' |w3m -T text/html
    In 5.1.2 (and others, I assume), the -f form silently drops the first argument after the script name from $_SERVER['argv']. I'd suggest avoiding it unless you need it for a special case.
    Adding a pause() function to PHP waiting for any user input returning it:
    <?php
    function pause() {
      $handle = fopen ("php://stdin","r");
      do { $line = fgets($handle); } while ($line == '');
      fclose($handle);
      return $line;
    }
    ?>
    
    When you're writing one line php scripts remember that 'php://stdin' is your friend. Here's a simple program I use to format PHP code for inclusion on my blog:
    UNIX:
     cat test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
    DOS/Windows:
     type test.php | php -r "print htmlentities(file_get_contents('php://stdin'));"
    To hand over the GET-variables in interactive mode like in HTTP-Mode (e.g. your URI is myprog.html?hugo=bla&bla=hugo), you have to call
    php myprog.html '&hugo=bla&bla=hugo'
    (two & instead of ? and &!)
    There just a little difference in the $ARGC, $ARGV values, but I think this is in those cases not relevant.
    When using the -R flag, the name of the variable containing the content of the current line (not including the LF) is $argn.
    For example you can do this code:
    cat file.txt | php -R 'echo $argn . "\n";'
    This will just output each line of the input file without doing anything to it.
    use " instead of ' on windows when using the cli version with -r
    php -r "echo 1" 
    -- correct
    php -r 'echo 1'
     PHP Parse error: syntax error, unexpected ''echo' (T_ENCAPSED_AND_WHITESPACE), expecting end of file in Command line code on line 1
    If you edit a php file in windows, upload and run it on linux with command line method. You may encounter a running problem probably like that:
    [root@ItsCloud02 wsdl]# ./lnxcli.php
    Extension './lnxcli.php' not present.
    Or you may encounter some other strange problem.
    Care the enter key. In windows environment, enter key generate two binary characters '0D0A'. But in Linux, enter key generate just only a 'OA'.
    I wish it can help someone if you are using windows to code php and run it as a command line program on linux.
    Here goes a very simple clrscr function for newbies...
    function clrscr() { system("clear"); }
    Spawning php-win.exe as a child process to handle scripting in Windows applications has a few quirks (all having to do with pipes between Windows apps and console apps).
    To do this in C++:
    // We will run php.exe as a child process after creating
    // two pipes and attaching them to stdin and stdout
    // of the child process
    // Define sa struct such that child inherits our handles
    SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES) };
    sa.bInheritHandle = TRUE;
    sa.lpSecurityDescriptor = NULL;
    // Create the handles for our two pipes (two handles per pipe, one for each end)
    // We will have one pipe for stdin, and one for stdout, each with a READ and WRITE end
    HANDLE hStdoutRd, hStdoutWr, hStdinRd, hStdinWr;
    // Now create the pipes, and make them inheritable
    CreatePipe (&hStdoutRd, &hStdoutWr, &sa, 0))
    SetHandleInformation(hStdoutRd, HANDLE_FLAG_INHERIT, 0);
    CreatePipe (&hStdinRd, &hStdinWr, &sa, 0)
    SetHandleInformation(hStdinWr, HANDLE_FLAG_INHERIT, 0);
    // Now we have two pipes, we can create the process
    // First, fill out the usage structs
    STARTUPINFO si = { sizeof(STARTUPINFO) };
    PROCESS_INFORMATION pi;
    si.dwFlags = STARTF_USESTDHANDLES;
    si.hStdOutput = hStdoutWr;
    si.hStdInput = hStdinRd;
    // And finally, create the process
    CreateProcess (NULL, "c:\\php\\php-win.exe", NULL, NULL, TRUE, NORMAL_PRIORITY_CLASS, NULL, NULL, &si, &pi);
    // Close the handles we aren't using
    CloseHandle(hStdoutWr);
    CloseHandle(hStdinRd);
    // Now that we have the process running, we can start pushing PHP at it
    WriteFile(hStdinWr, "<?php echo 'test'; ?>", 9, &dwWritten, NULL);
    // When we're done writing to stdin, we close that pipe
    CloseHandle(hStdinWr);
    // Reading from stdout is only slightly more complicated
    int i;
    std::string processed("");
    char buf[128];
    while ( (ReadFile(hStdoutRd, buf, 128, &dwRead, NULL) && (dwRead != 0)) ) {
      for (i = 0; i < dwRead; i++)
        processed += buf[i];
    }  
    // Done reading, so close this handle too
    CloseHandle(hStdoutRd);
    A full implementation (implemented as a C++ class) is available at http://www.stromcode.com
    I was looking for a way to interactively get a single character response from user. Using STDIN with fread, fgets and such will only work after pressing enter. So I came up with this instead:
    #!/usr/bin/php -q
    <?php
    function inKey($vals) {
      $inKey = "";
      While(!in_array($inKey,$vals)) {
        $inKey = trim(`read -s -n1 valu;echo \$valu`);
      }
      return $inKey;
    }
    function echoAT($Row,$Col,$prompt="") {
      // Display prompt at specific screen coords
      echo "\033[".$Row.";".$Col."H".$prompt;
    }
      // Display prompt at position 10,10
      echoAT(10,10,"Opt : ");
      // Define acceptable responses
      $options = array("1","2","3","4","X");
      // Get user response
      $key = inKey($options);
      // Display user response & exit
      echoAT(12,10,"Pressed : $key\n");
    ?>
    Hope this helps someone.
    an another "another variant" :
    <?php
    function arguments($argv)
    {
     $_ARG = array();
     foreach ($argv as $arg)
     {
      if (preg_match('#^-{1,2}([a-zA-Z0-9]*)=?(.*)$#', $arg, $matches))
      {
       $key = $matches[1];
       switch ($matches[2])
       {
        case '':
        case 'true':
         $arg = true;
         break;
        case 'false':
         $arg = false;
         break;
        default:
         $arg = $matches[2];
       }
       $_ARG[$key] = $arg;
      }
      else
      {
       $_ARG['input'][] = $arg;
      }
     }
     return $_ARG;
    }
    ?>
    $php myscript.php arg1 -arg2=val2 --arg3=arg3 -arg4 --arg5 -arg6=false
    Array
    (
      [input] => Array
        (
          [0] => myscript.php
          [1] => arg1
        )
      [arg2] => val2
      [arg3] => arg3
      [arg4] => true
      [arg5] => true
      [arg5] => false
    )
    dunno if this is on linux the same but on windows evertime
    you send somthing to the console screen php is waiting for
    the console to return. therefor if you send a lot of small 
    short amounts of text, the console is starting to be using 
    more cpu-cycles then php and thus slowing the script.
    take a look at this sheme:
    cpu-cycle:1 ->php: print("a");
    cpu-cycle:2 ->cmd: output("a");
    cpu-cycle:3 ->php: print("b");
    cpu-cycle:4 ->cmd: output("b");
    cpu-cycle:5 ->php: print("c");
    cpu-cycle:6 ->cmd: output("c"); 
    cpu-cylce:7 ->php: print("d");
    cpu-cycle:8 ->cmd: output("d"); 
    cpu-cylce:9 ->php: print("e");
    cpu-cycle:0 ->cmd: output("e"); 
    on the screen just appears "abcde". but if you write 
    your script this way it will be far more faster:
    cpu-cycle:1 ->php: ob_start();
    cpu-cycle:2 ->php: print("abc");
    cpu-cycle:3 ->php: print("de");
    cpu-cycle:4 ->php: $data = ob_get_contents();
    cpu-cycle:5 ->php: ob_end_clean();
    cpu-cycle:6 ->php: print($data);
    cpu-cycle:7 ->cmd: output("abcde");
    now this is just a small example but if you are writing an
    app that is outputting a lot to the console, i.e. a text
    based screen with frequent updates, then its much better 
    to first cach all output, and output is as one big chunk of
    text instead of one char a the time. 
    ouput buffering is ideal for this. in my script i outputted
    almost 4000chars of info and just by caching it first, it
    speeded up by almost 400% and dropped cpu-usage.
    because what is being displayed doesn't matter, be it 2
    chars or 40.0000 chars, just the call to output takes a 
    great deal of time. remeber that.
    maybe someone can test if this is the same on unix-based
    systems. it seems that the STDOUT stream just waits for 
    the console to report ready, before continueing execution.
    One of the things I like about perl and vbscripts, is the fact that I can name a file e.g. 'test.pl' and just have to type 'test, without the .pl extension' on the windows command line and the command processor knows that it is a perl file and executes it using the perl command interpreter.
    I did the same with the file extension .php3 (I will use php3 exclusivelly for command line php scripts, I'm doing this because my text editor VIM 6.3 already has the correct syntax highlighting for .php3 files ).
    I modified the PATHEXT environment variable in Windows XP, from the " 'system' control panel applet->'Advanced' tab->'Environment Variables' button-> 'System variables' text area".
    Then from control panel "Folder Options" applet-> 'File Types' tab, I added a new file extention (php3), using the button 'New' and typing php3 in the window that pops up.
    Then in the 'Details for php3 extention' area I used the 'Change' button to look for the Php.exe executable so that the php3 file extentions are associated with the php executable.
    You have to modify also the 'PATH' environment variable, pointing to the folder where the php executable is installed
    Hope this is useful to somebody
    In *nix systems, use the WHICH command to show the location of the php binary executable. This is the path to use as the first line in your php shell script file. (#!/path/to/php -q) And execute php from the command line with the -v switch to see what version you are running.
    example:
    # which php
    /usr/local/bin/php
    # php -v
    PHP 4.3.1 (cli) (built: Mar 27 2003 14:41:51)
    Copyright (c) 1997-2002 The PHP Group
    Zend Engine v1.3.0, Copyright (c) 1998-2002 Zend Technologies
    In the above example, you would use: #!/usr/local/bin/php
    Also note that, if you do not have the current/default directory in your PATH (.), you will have to use ./scriptfilename to execute your script file from the command line (or you will receive a "command not found" error). Use the ENV command to show your PATH environment variable value.
    To display colored text when it is actually supported :
    <?php
    echo "\033[31m".$myvar; // red foreground
    echo "\033[41m".$myvar; // red background
    ?>
    To reset these settings : 
    <?php
    echo "\033[0m";
    ?>
    More fun :
    <?php
    echo "\033[5;30m;\033[48mWARNING !"; // black blinking text over red background
    ?>
    More info here : http://www.tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html
    Assuming --prefix=/usr/local/php, it's better to create a symlink from /usr/bin/php or /usr/local/bin/php to target /usr/local/php/bin/php so that it's both in your path and automatically correct every time you rebuild. If you forgot to do that copy of the binary after a rebuild, you can do all kinds of wild goose chasing when things break.

    内置Web Server

    PHP 5.4.0起, CLI SAPI 提供了一个内置的Web服务器。

    这个内置的Web服务器主要用于本地开发使用,不可用于线上产品环境。

    URI请求会被发送到PHP所在的的工作目录(Working Directory)进行处理,除非你使用了-t参数来自定义不同的目录。

    如果请求未指定执行哪个PHP文件,则默认执行目录内的index.php 或者 index.html。如果这两个文件都不存在,服务器会返回404错误。

    当你在命令行启动这个Web Server时,如果指定了一个PHP文件,则这个文件会作为一个“路由”脚本,意味着每次请求都会先执行这个脚本。如果这个脚本返回 FALSE ,那么直接返回请求的文件(例如请求静态文件不作任何处理)。否则会把输出返回到浏览器。

    Example #1 启动Web服务器

    $ cd ~/public_html
    $ php -S localhost:8000

    终端窗口会显示:

    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
    

    接着访问http://localhost:8000/和http://localhost:8000/myscript.html,窗口会显示:

    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 read
    

    Example #2 启动时指定根目录

    $ cd ~/public_html
    $ php -S localhost:8000 -t foo/

    终端窗口显示:

    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 quit
    

    Example #3 使用路由(Router)脚本

    请求图片直接显示图片,请求HTML则显示“Welcome to PHP”

    <?php
    // router.php
    if (preg_match('/\.(?:png|jpg|jpeg|gif)$/', $_SERVER["REQUEST_URI"]))
        return false;    // 直接返回请求的文件
    else { 
        echo "<p>Welcome to PHP</p>";
    }
    ?>
    
    $ php -S localhost:8000 router.php

    执行之后终端显示:

    PHP 5.4.0 Development Server started at Thu Jul 21 10:53:19 2011
    Listening on localhost:8000
    Document root is /home/me/public_html
    Press Ctrl-C to quit.
    [Thu Jul 21 10:53:45 2011] ::1:55801 GET /mylogo.jpg - Request read
    [Thu Jul 21 10:53:52 2011] ::1:55803 GET /abc.html - Request read
    [Thu Jul 21 10:53:52 2011] ::1:55804 GET /favicon.ico - Request read
    
    In order to set project specific configuration options, simply add a php.ini file to your project, and then run the built-in server with this flag:
    php -S localhost:8000 -c php.ini
    This is especially helpful for settings that cannot be set at runtime (ini_set()).
    I painfully experienced behaviour that I can't seem to find documented here so I wanted to save everyone from repeating my mistake by giving the following heads up:
    When starting php -S on a mac (in my case macOS Sierra) to host a local server, I had trouble with connecting from legacy Java. 
    As it turned out, if you started the php server with 
    "php -S localhost:80" 
    the server will be started with ipv6 support only!
    To access it via ipv4, you need to change the start up command like so:
     "php -S 127.0.0.1:80"
    which starts server in ipv4 mode only.
    It’s not mentioned directly, and may not be obvious, but you can also use this to create a virtual host. This, of course, requires the help of your hosts file.
    Here are the steps:
    1  /etc/hosts
      127.0.0.1  www.example.com
    2  cd [root folder]
      php -S www.example.com:8000
    3  Browser:
      http://www.example.com:8000/index.php
    Combined with a simple SQLite database, you have a very handy testing environment.
    If your URI contains a dot, you'll lose the $_SERVER['PATH_INFO'] variable, when using the built-in webserver.
    I wanted to write an API, and use .json ending in the URI-s, but then the framework's routing mechanism broke, and it took a lot of time to discover that the reason behind it was its router relying on $_SERVER['PATH_INFO'].
    References:
    https://bugs.php.net/bug.php?id=61286
    To output debugging information on the command line you can write output to php://stdout:
    <?php
    $path = $_SERVER["SCRIPT_FILENAME"];
    file_put_contents("php://stdout", "\nRequested: $path");
    echo "<p>Hello World</p>";
    ?>
    
    On Windows you may find useful to have a phpserver.bat file in shell:sendto with the folowing:
    explorer http://localhost:8888
    rem check if arg is file or dir
    if exist "%~1\" (
     php -S localhost:8888 -t "%~1"
    ) else (
     php -S localhost:8888 -t "%~dp1"
    )
    then for fast web testing you only have to SendTo a file or folder to this bat and it will open your explorer and run the server.
    Just a note to people who also use windows 8.1, or anyone who has had this problem when running the using the PHP server CLI.
    `PHP -S localhost:8000 -t /public` <-- Not going to work.
    `PHP -S localhost:8000 -t public` <-- Works!
    And there is something else up in the notes saying something about you can't serve a project folder and a router file. Well, actually you can! At least for me.
    `PHP -S localhost:8000 router.php -t public` <-- Perhaps someone tries this and it doesn't work.
    `PHP -S localhost:8000 -t public router.php` <-- Works!
    To send environment variable as long as with PHP built-in web server, type like this.
    ~$ MYENV=dev php -d variables_order=EGPCS -S 0.0.0.0:8000
    On PHP script we can check with this code.
    <?php
     echo getenv('MYENV'); // print dev
    $_SERVER['SERVER_ADDR'] is not defined when using php as the built-in commandline web server, so you can not use $_SERVER['SERVER_ADDR'] to detect the Server's IP address.
    P.S.: This is tested on Windows with PHP 7.1 on 2016-12-22.
    Below is the printed $_SERVER variable.
    Array
    (
      [DOCUMENT_ROOT] => E:\Programs\PHPServer\www\srv
      [REMOTE_ADDR] => 118.117.61.32
      [REMOTE_PORT] => 10865
      [SERVER_SOFTWARE] => PHP 7.1.0 Development Server
      [SERVER_PROTOCOL] => HTTP/1.1
      [SERVER_NAME] => 0.0.0.0
      [SERVER_PORT] => 8080
      [REQUEST_URI] => /
      [REQUEST_METHOD] => GET
      [SCRIPT_NAME] => /index.php
      [SCRIPT_FILENAME] => E:\Programs\PHPServer\www\srv\index.php
      [PHP_SELF] => /index.php
      [HTTP_HOST] => www.wuxiancheng.cn:8080
      [HTTP_CONNECTION] => keep-alive
      [HTTP_CACHE_CONTROL] => max-age=0
      [HTTP_UPGRADE_INSECURE_REQUESTS] => 1
      [HTTP_USER_AGENT] => Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36
      [HTTP_ACCEPT] => text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
      [HTTP_DNT] => 1
      [HTTP_ACCEPT_ENCODING] => gzip, deflate, sdch
      [HTTP_ACCEPT_LANGUAGE] => zh-CN,zh;q=0.8,en-US;q=0.6,en;q=0.4
      [HTTP_COOKIE] => qbbs_2132_saltkey=fZ7509n5; qbbs_2132_lastvisit=1482156014; Hm_lvt_f812a4362ef73c80c4d13485d1ab3a49=1482159614; _ga=GA1.2.1594404236.1482159615; su=727vL6EEPLqjcyfJcad-za9eVYOh1i7e; Hm_lvt_6a65b0f2004e441e86ecea9c3562d997=1482232509,1482241896,1482242293,1482296586
      [REQUEST_TIME_FLOAT] => 1482390410.65625
      [REQUEST_TIME] => 1482390410
    )
    I fiddled around with the internal webserver and had issues regarding handling static files, that do not contain a dot and a file extension.
    The webserver responded with 200 without any content for files with URIs like "/testfile".
    I am not certain if this is a bug, but I created a router.php that now does not use the "return false;" operation in order to pass thru the static file by the internal webserver.
    Instead I use fpassthru() to do that.
    In addition to that, my router.php can be configured to...
    - ... have certain index files, when requesting a directory
    - ... configure regex routes, so that, if the REQUEST_URI matches the regex, a certain file or directory is requested instead. (something you would do with nginx config or .htaccess ModRewrite)
    Maybe someone finds this helpful.
    ================================
    <?php
    $indexFiles = ['index.html', 'index.php'];
    $routes = [
     '^/api(/.*)?$' => '/index.php'
    ];
    $requestedAbsoluteFile = dirname(__FILE__) . $_SERVER['REQUEST_URI'];
    // check if the the request matches one of the defined routes
    foreach ($routes as $regex => $fn)
    {
     if (preg_match('%'.$regex.'%', $_SERVER['REQUEST_URI']))
     {
      $requestedAbsoluteFile = dirname(__FILE__) . $fn;
      break;
     }
    }
    // if request is a directory call check if index files exist
    if (is_dir($requestedAbsoluteFile))
    {
     foreach ($indexFiles as $filename)
     {
      $fn = $requestedAbsoluteFile.'/'.$filename;
      if (is_file($fn))
      {
       $requestedAbsoluteFile = $fn;
       break;
      }
     }
    }
    // if requested file does not exist or is directory => 404
    if (!is_file($requestedAbsoluteFile))
    {
     header($_SERVER['SERVER_PROTOCOL'].' 404 Not Found');
     printf('"%s" does not exist', $_SERVER['REQUEST_URI']);
     return true;
    }
    // if requested file is'nt a php file
    if (!preg_match('/\.php$/', $requestedAbsoluteFile)) {
     header('Content-Type: '.mime_content_type($requestedAbsoluteFile));
     $fh = fopen($requestedAbsoluteFile, 'r');
     fpassthru($fh);
     fclose($fh);
     return true;
    }
    // if requested file is php, include it
    include_once $requestedAbsoluteFile;
    My routing file looks like this: 
    if (file_exists($_SERVER["DOCUMENT_ROOT"] . $_SERVER["REQUEST_URI"])) {
      return false;
    } else {
      require "index.php";
    }
    The reason is to support all static files.
    Note that to listen on a naked IPv6 address, you have to strangely enclose the address in so-called square brackets. Example:
    $ php -S [9990:116:a001:1900::1001]:8080 -t web/
    Do NOT use the -t option if you want to use a router script, you can change current working directory to the web document root before launching the php built-in web server.
    [works fine]
    cd /d C:\Web\Server
    php -S www.51-n.com:80 router.php -n -d expose_php=0 -d display_errors=0 -d extension_dir="ext"
    [always gets a 500 error]
    php -S www.51-n.com:80 router.php -t C:\Web\Server -n -d expose_php=0 -d display_errors=0 -d extension_dir="ext"
    when I need to up a server for develop with rewrite, I use it:
    // php -S 0.0.0.0:8080 -file webServer.php
    // webServer.php
    <?php
    if (preg_match('/\.css|\.js|\.jpg|\.png|\.map$/', $_SERVER['REQUEST_URI'], $match)) {
      $mimeTypes = [
        '.css' => 'text/css',
        '.js' => 'application/javascript',
        '.jpg' => 'image/jpg',
        '.png' => 'image/png',
        '.map' => 'application/json'
      ];
      $path = __DIR__ . $_SERVER['REQUEST_URI'];
      if (is_file($path)) {
        header("Content-Type: {$mimeTypes[$match[0]]}");
        require $path;
        exit;
      }
    }
    require_once __DIR__.'/../app/bootstrap.php';
    I improved Ivan Ferrer's phpserver.bat to open the Send To'd files in the browser directly:-
    rem check if arg is file or dir
    if exist "%~1\" (
     explorer http://localhost:8888
     php -S localhost:8888 -t "%~1"
    ) else (
     explorer http://localhost:8888/%~nx1
     php -S localhost:8888 -t "%~dp1"
    )
    You can also print messages to the server's STDOUT via error_log().
    Also the documentation doesn't make it clear that when you use router script if a PHP file is requested and you return false, the PHP file will be served (i.e. you do not need to load and eval it manually).
    I have found a strange issue while executing shell scripts on my Mac (High Sierra), PHP 7.2 with both the server and Laravel Valet.
    It seems like the PATH=/usr/bin:/bin:/usr/sbin:/sbin which are the default Mac paths, but does not take into account the shell path from my .bash_profile which means that mysql and other utilities cannot be found.
    Is there any workaround for injecting a PATH variable on execution
    if you encountered this error:
    Unknown: php_network_getaddresses: getaddrinfo failed
    try this:
    1. make sure you have a `localhost` entry in your hosts file
    2. or use `php -S 127.0.0.1:8888`
    For serving static content like .css or .js and otherwise using a router (for me it was index.php) this worked out of the box for me:
      php -S localhost:8000 
    Due to my router file was index.php. But 
      php -S localhost:8000 index.php 
    did not work, because my static files are not served via my router.
    In order to set project specific configuration options, simply add a php.ini file to your project, and then run the built-in server with this flag:
    php -S localhost:8000 -c php.ini
    This is especially helpful for settings that cannot be set at runtime (ini_set()).
    Note: The built-in web server has a file size limit. For files larger than 5 GB, it will always serve a "File not found" error page.
    submit_btn.addEventListener(MouseEvent.CLICK, sendMessage);
    function sendMessage(e:MouseEvent): void{
    var my_vars:URLVariables = new URLVariables();
    my_vars.senderName = name_txt.text;
    my_vars.senderEmail = email_txt.text;
    my_vars.senderMsg = message_txt.text;
    var my_url:URLRequest = new URLRequest("mail.php");
    my_url.method = URLRequestMethod.POST;
    my_url.data = my_vars;
    var my_loader:URLLoader = new URLLoader();
    my_loader.dataFormat = URLLoaderDataFormat.VARIABLES;
    my_loader.load(my_url);
    name_txt.text = "";
    email_txt.text = "";
    message_txt.text = "Message Sent";
    }

    INI 配置

    CLI SAPI 配置选项
    名字默认可修改范围更新日志
    cli_server.color"0"PHP_INI_ALLPHP 5.4.0. 起生效

    这是配置指令的简短说明。

    cli_server.colorboolean

    控制内置Web Server的终端输出有无颜色。

    上篇:安全模式

    下篇:垃圾回收机制