PHP的命令行模式详解(在shell中运行php语句或者文件)

参考  https://www.php.cn/php-weizijiaocheng-387936.html

PHP 的命令行模式能使得 PHP 脚本能完全独立于 WEB 服务器单独运行。

php命令行模式的选项参数可以使用以下命令查看

php --help
php -h
[vagrant@vmp2-local-dva01 ~]$ php --help
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 as interactive shell
  -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               Output HTML syntax highlighted source.
  -v               Version number
  -w               Output source with stripped comments and whitespace.
  -z <file>        Load Zend extension <file>.

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

  --ini            Show configuration file names

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

选项参数有些多,之说几个比较常用的

1:  php -i

该命令行参数会调用 phpinfo() 函数,并打印出结果。

2:  php -a

进入交互模式。范例如下,进入交互模式后,可以直接输入php语句,执行并输出结果。注意,php语句结束要有分号

[vagrant@vmp2-local-dva01 ~]$ php -a
Interactive shell

php > echo "test"
php > ;
test
3:  php -r "php语句;"

该语句可以直接在命令行中执行php语句。注意,php语句后面要有分号。范例如下

[vagrant@vmp2-local-dva01 ~]$ php -r "echo \"test\n\";"
test

另外,可以在shell脚本中执行php语句,并获取php语句的输出结果,范例如下

#!/bin/bash
result=$(php -r "echo 'test';") echo $result
4:  php [-f] php文件名

该命令可以直接在命令行中执行php文件,范例如下

[vagrant@vmp2-local-dva01 ~]$ echo '<?php echo "test\n"; ?>' > test.php
[vagrant@vmp2-local-dva01 ~]$ cat test.php
<?php echo "test\n"; ?>
[vagrant@vmp2-local-dva01 ~]$ php test.php
test
[vagrant@vmp2-local-dva01 ~]$ php -f test.php
test
[vagrant@vmp2-local-dva01 ~]$ 

另外,可以在shell脚本中执行php文件

#!/bin/bash
result=$(php test.php)
echo $result
5:  php -h 或者 php --help

该命令即文章开头的命令,显示php的帮助信息

猜你喜欢

转载自www.cnblogs.com/gaoBlog/p/12325336.html