文字

PHP 在 Microsoft Windows 下的命令行方式

本章包含有针对在 Windows 下以命令行运行 PHP 的说明与提示。

Note:

应该先阅读手工安装步骤!

要在命令行下运行 PHP,可以无需对 Windows 做任何改动。

C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

但是有几个很容易的步骤可以使其更加简便。某些步骤可能已经在之前完成了,不过还是在这里重复说明以便提供一个完整的步骤序列。

    Note:

    PATH PATHEXT 都是在 Windows 下已有的重要环境变量,要留意不要覆盖了其内容,仅仅是向其中添加内容。

  • 将 PHP 可执行文件(php.exephp-win.exe 或者 php-cli.exe)的路径添加到 PATH 环境变量中去。如何将 PHP 目录添加到 PATH 中请参阅与之相关的常见问题。

  • .PHP 后缀添加到 PATHEXT 环境变量中去。可以在修改 PATH 环境变量时同时进行。跟常见问题中说明的步骤一样,不要要修改的是 PATHEXT 环境变量而不是 PATH 环境变量。

    Note:

    .PHP 放置到什么位置将决定具有相同文件名时运行的优先级。例如将 .PHP 放到 .BAT 之前将导致如果有同名的 PHP 脚本和批处理文件,则 PHP 脚本会运行。

  • .PHP 后缀关联为一种文件类型,用以下命令完成:

    assoc .php=phpfile
    
  • phpfile 文件类型关联到适当的 PHP 可执行文件,用以下命令完成:

    ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2
    

按照以上步骤将使 PHP 脚本可以在任何目录下运行,不需要输入 PHP 可执行文件名以及 .PHP 后缀,并且所有参数都会被传递给脚本来处理。

以下例子说明了可以手工修改的注册表项目变化。

Example #1 注册表变化

Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\PHP5\\php-win.exe,0"[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"

有了这些改变之后,本页顶端第一个例子中的命令可以写成这样:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
或者如果 "C:\PHP Scripts" 路径位于 PATH 环境变量中的话:
script -arg1 -arg2 -arg3

Note:

不过如果想要通过此技巧将 PHP 脚本作为命令行管道过滤器的话,有个小问题。例如以下例子:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
或者
dir | script -arg1 -arg2 -arg3
此时脚本会死掉,没有输出任何内容。要解决此问题,还需要做一个注册表修改。
Windows Registry Editor Version 5.00[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
有关此问题的更多信息见» 微软知识库文章:321788。

用户评论:

[#1] elhadjouattara at gmail dot thrcom [2015-04-26 17:47:48]

On Windows 8, with php 5.6.8 win32 VC11 in command line, need to indicate path with / rather than backslash \
Hence C:\Users\toshiba\Documents\php\test.php shall be C:/Users/toshiba/Documents/php/test.php

[#2] ckelley at ca-cycleworks dot com [2012-04-01 00:43:07]

Note that the default behavior of php-cli is short_open_tag=off, which means PHP scripts using short tags ` <?php  ?> ` won't execute and instead show source code.

To fix this, you must edit the php.ini file and add short_open_tag=on

[#3] pimroes at gmail dot com [2011-01-11 00:11:48]

Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.

上一篇: 下一篇: