php 使用PHP执行cmd命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11209509/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 23:58:40  来源:igfitidea点击:

Using PHP to execute cmd commands

phpcmdshell-exec

提问by Wern Ancheta

How do I properly execute commands in the command line using php? For example I'm using the command below in the command line to convert a docx file into a pdf file:

如何使用 php 在命令行中正确执行命令?例如,我在命令行中使用以下命令将 docx 文件转换为 pdf 文件:

pdfcreator.exe /PF"D:\Documents\sample.docx

Now using PHP code I want to be able to execute the same command but nothing seems to be happening:

现在使用 PHP 代码,我希望能够执行相同的命令,但似乎什么也没发生:

<?php
shell_exec('pdfcreator.exe /PF"D:\Documents\sample.docx"');
?>

Is this possible in PHP?If yes, how do I do it?

这在 PHP 中可能吗?如果是,我该怎么做?

回答by Piotr Olaszewski

system("c:\path\to\pdfcreator.exe /PF\"D:\Documents\sample.docx""); 

try this.

尝试这个。

回答by Mike Mackintosh

Don't forget to escape your command with escapeshellcmd(). This will prevent you from having to use ugly backslashes and escape characters.

不要忘记使用escapeshellcmd()转义您的命令。这将防止您不得不使用丑陋的反斜杠和转义字符。

There are also other alternatives which may work:

还有其他可能有效的替代方法:

`command` // back ticks drop you out of PHP mode into shell
exec('command', $output); // exec will allow you to capture the return of a command as reference
shell_exec('command'); // will return the output to a variable
system(); //as seen above.

Also, make sure your .exe is included within your $PATH variable. If not, include the full path for the command.

另外,请确保您的 .exe 包含在您的 $PATH 变量中。如果没有,请包含命令的完整路径。