使用PHP执行cmd命令

Wer*_*eta 7 php cmd shell-exec

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

pdfcreator.exe /PF"D:\Documents\sample.docx
Run Code Online (Sandbox Code Playgroud)

现在使用PHP代码我希望能够执行相同的命令,但似乎没有发生任何事情:

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

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

Pio*_*ski 9

system("c:\\path\\to\\pdfcreator.exe /PF\"D:\\Documents\\sample.docx""); 
Run Code Online (Sandbox Code Playgroud)

试试这个.


Mik*_*osh 5

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

还有其他替代方案可行:

`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.
Run Code Online (Sandbox Code Playgroud)

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