Use PHP as Command Line Shell

风行水上 @ 2014-03-19 18:25:56
标签:

    PHP CLI

    % php -v
    
    PHP 5.4.12 (cli) (built: Mar  7 2013 01:50:33)
    Copyright (c) 1997-2013 The PHP Group
    Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies
    

    上面括号中显示的"(cli)"表明这是一个CLI SAPI模式下的PHP。

    CLI模式下的PHP相当于:php -C -q

    • "-q" : 不输出HTTP Header
    • "-C" : 不切换到程序所在目录
    • "max_execution_time = 0" : 不限制运行时间

    常见问题

    需要指定ini设置

    PHP CLI默认可能是不加载任何ini文件的。这可能会带来一些问题,比如:

    Warning: date(): It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in Command line code on line 1

    设置ini变量有两种办法:

    • php -c $file_or_dir : 加载指定的'php.ini'文件
    • php -d key=value : 通过命令行指定

    使用$_GET传递命令行参数

    parse_str(implode('&', array_slice($argv, 1)), $_GET);
    

    命令行程序的用法为:php script.php a=b c=d

    为了避免在每个脚本中都加入上述文件,可以借助auto_prepend_file设置:

    # File: /some/path/lib/php/php.cli.ini
    
    date.timezone  = "US/Pacific"
    auto_prepend_file = "/some/path/lib/php/cli.prepend.php"
    
    # File: ~/.cshrc
    
    alias  php php -c /some/path/lib/php/php.cli.ini
    

    Use PHP Builtin Web Server

    php -S localhost:8888 -t /some/path/to/doc/root
    

    Use PHP like Sed & Awk

    php -R 'echo "Line $argi = $argn";'
    
    
    php -B 'echo "Begin";' -E 'echo "End";' -R 'echo "Line $argi = $argn";'
    

    Use Interactive Mode

    从PHP 5.1.0开始可以使用交互模式的PHP Shell。

    php -a
    

    如果没有看到"php >"提示符,而只是显示"Interactive mode enabled",则说明Interactive Mode实际上没有被编译进去。

    Standard Input/Output

    Nothing special than PHP Stream.

    $stdin  = fopen('php://stdin', 'r');
    $stdout = fopen('php://stdout', 'w');
    $stderr = fopen('php://stderr', 'w');
    
    标签:

      分享到:
      comments powered by Disqus

      27/30ms