从 PHP 问题在 Windows 中执行 cmd 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3099971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Executing cmd commands in Windows from PHP Issue
提问by Richard Knop
Is it possible to execute cmd commands in Windows OS with PHP exec() function?
是否可以使用 PHP exec() 函数在 Windows 操作系统中执行 cmd 命令?
I tried this:
我试过这个:
<?php
try {
echo exec(
'O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test3.pdf'
);
} catch (Exception $e) {
echo $e->getMessage();
}
Basically, I'm trying to merge two pdf files with the pdftk program. If I just write the same exact command to the cmd by hand, it works and the O:\test\123.pdf file is created. But when I execute the above PHP file, nothing happens (blank page, the file is not created).
基本上,我正在尝试将两个 pdf 文件与 pdftk 程序合并。如果我只是手动将完全相同的命令写入 cmd,它就可以工作并创建 O:\test\123.pdf 文件。但是当我执行上面的 PHP 文件时,没有任何反应(空白页面,没有创建文件)。
回答by Andy
Can your PHP user access cmd.exe? You might find the tools at Microsoft's Sysinternalsvery useful; particularly the process monitor.
您的 PHP 用户可以访问 cmd.exe 吗?您可能会发现Microsoft Sysinternals 中的工具非常有用;特别是过程监视器。
回答by Andy E
Try escaping the directory separator:
尝试转义目录分隔符:
exec("O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf");
Or even better, use single quotes instead:
或者更好的是,改用单引号:
exec('O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test3.pdf');
回答by MerlinTheMagic
Here is a project that allows PHP to obtain and interact dynamically with a real cmd terminal. Get it here: https://github.com/merlinthemagic/MTS
这里有一个项目,可以让 PHP 获取真正的 cmd 终端并与之动态交互。在这里获取:https: //github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
下载后,您只需使用以下代码:
//if you prefer Powershell, replace 'cmd' with 'powershell'
$shellObj = \MTS\Factories::getDevices()->getLocalHost()->getShell('cmd');
$strCmd1 = 'O:\test\pdftk.exe O:\test\outputs\OPP\out.pdf O:\test\outputs\OPP\out2.pdf cat output O:\test\123.pdf';
$return1 = $shellObj->exeCmd($strCmd1);
The return will give you the command return OR error from cmd, just as if you sat at the console. Furthermore, you can issue any command you like against the $shellObj, the environment is maintained throughout the life of the PHP script. So instead of bundling commands in a script file, just issue them one by one using the exeCmd() method, that way you can also handle the return and any exceptions.
返回将为您提供来自 cmd 的命令 return OR 错误,就像您坐在控制台前一样。此外,您可以针对 $shellObj 发出您喜欢的任何命令,该环境将在 PHP 脚本的整个生命周期中得到维护。因此,不要将命令捆绑在脚本文件中,只需使用 exeCmd() 方法一个一个地发出它们,这样您也可以处理返回和任何异常。
回答by Someone
try Executing using the Admin Privileges for command prompt
尝试使用管理员权限执行命令提示符