Executing PHP files

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

  1. 让 PHP 运行指定文件。

    php my_script.php
    
    php -f my_script.php
    

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

    注意:

    If arguments need to be passed to the script when using -f, the first argument must be --.

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

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

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

    注意:

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

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

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

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

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

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

另外,全局变量 $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 脚本一样被直接执行。

示例 #1 Execute PHP script as shell script

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

示例 #2 试图以命令行方式运行的 PHP 脚本(script.php)

#!/usr/bin/php
<?php

if ($argc != || 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 头信息输出。

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

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

示例 #3 运行 PHP 命令行脚本的批处理文件(script.bat)

@echo OFF
"C:\php\php.exe" script.php %*

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

请参阅 Readline 扩展模块的有关文档,以获取更多的函数的信息。这些函数可以帮助完善 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".

add a note add a note

User Contributed Notes 7 notes

up
48
php at richardneill dot org
11 years ago
On Linux, the shebang (#!) line is parsed by the kernel into at most two parts.
For example:

1:  #!/usr/bin/php
2:  #!/usr/bin/env  php
3:  #!/usr/bin/php -n
4:  #!/usr/bin/php -ddisplay_errors=E_ALL
5:  #!/usr/bin/php -n -ddisplay_errors=E_ALL

1. is the standard way to start a script. (compare "#!/bin/bash".)

2. uses "env" to find where PHP is installed: it might be elsewhere in the $PATH, such as /usr/local/bin.

3. if you don't need to use env, you can pass ONE parameter here. For example, to ignore the system's PHP.ini, and go with the defaults, use "-n". (See "man php".)

4.  or, you can set exactly one configuration variable. I recommend this one, because display_errors actually takes effect if it is set here. Otherwise, the only place you can enable it is system-wide in php.ini. If you try to use ini_set() in your script itself, it's too late: if your script has a parse error, it will silently die.

5. This will not (as of 2013) work on Linux. It acts as if the whole string, "-n -ddisplay_errors=E_ALL" were a single argument. But in BSD, the shebang line can take more than 2 arguments, and so it may work as intended.

Summary: use (2) for maximum portability, and (4) for maximum debugging.
up
2
gabriel at figdice dot org
7 years ago
Regarding shebang:

In both Linux and Windows, when you execute a script in CLI with:

    php script.php

then PHP will ignore the very first line of your script if it starts with:

    #!

So, this line is not only absorbed by the kernel when the script file is executable, but it is also ignored by the PHP engine itself.

However, the engine will NOT ignore the first #! line of any included files withing your "outer" script.php.
Any "shebang" line in an included script, will result in simply outputting the line to STDOUT, just as any other text residing outside a <?php ...  ?> block.
up
2
david at frankieandshadow dot com
7 years ago
A gotcha when using #!/usr/bin/php at the start of the file as noted above:

if you originally edited the file on Windows and then attempt to use it on Unix, it won't work because the #! line requires a Unix line ending. Bash gives you the following error message if it has DOS line endings:
"bash: /usr/local/bin/wpreplace.php: /usr/bin/php^M: bad interpreter: No such file or directory"

(In Emacs I used "CTRL-X ENTER f" then type "unix" and ENTER to convert)
up
1
email at alexander-bombis dot de
3 years ago
For Windows:

After the years I also have the fact that I have to use double quotation marks after php -r on Windows shell.

But in the Powershell you can use single or double quotation!
up
-2
petruzanautico at yah00 dot com dot ar
12 years ago
As you can't use -r and -f together, you can circumvent this by doing the following:
php -r '$foo = 678; include("your_script.php");'
up
-3
spencer at aninternetpresence dot net
12 years ago
If you are running the CLI on Windows and use the "-r" option, be sure to enclose your PHP code in double (not single) quotes. Otherwise, your code will not run.
up
-3
synnus at gmail dot com
5 years ago
in php.ini use auto_prepend_file="init.php"
first start script
To Top