PHP 在 Microsoft Windows 下的命令行方式

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


应该先阅读 手工安装步骤

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

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



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

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

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


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

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

    assoc .php=phpfile

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

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

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


示例 #1 注册表变化

Windows Registry Editor Version 5.00

"Content Type"="application/php"

@="PHP Script"




@="\"C:\\php\\php.exe\" -f \"%1\" -- %~2"


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


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

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
dir | script -arg1 -arg2 -arg3
Windows Registry Editor Version 5.00

有关此问题的更多信息见» 微软知识库文章:321788。 从 Windows 10 开始,此设置似乎被颠倒,请参考以下链接 »  Microsoft 论坛帖子

add a note

User Contributed Notes 3 notes

pimroes at gmail dot com
13 years ago
Make sure your run CMD.exe as an administrator, otherwise you'll get an "access denied" when you run the commands.
rudigerw at hotmail dot com
8 years ago
On Windows 10 starting php by only typing the script name in an elevated command prompt pops up a dialog to choose an app.
It turns out Windows does that when the program associated with phpfiles through ftype cannot be executed. In this case this happens because it is trying to run php.exe in non-admin mode, even when launched from an elevated command prompt. To fix this, locate your php.exe, right-click, "Properties", "Compatibility", under Settings check "Run this program as an administrator; then also click "Change settings for all users".
vechenjivot at gmail dot com
8 years ago
On Windows 10, the above registry entries didn't work for me. In order for them to work, you need to write to
for which you don't have access, even if you run regedit as admin (probably because of the Hash key).
The solution is actually much easier - right-click a PHP file in Explorer and associate it to always open with php.exe.
And then you need to modify the PATH variable:
setx PATH "%PATH%;c:\path\to\php" /M
if you want to execute files with commands like
php file.php
To Top