使用PHP执行cmd命令

10
我该如何使用php在命令行中正确执行命令?例如,我正在使用以下命令将docx文件转换为pdf文件:
pdfcreator.exe /PF"D:\Documents\sample.docx

现在,我想使用PHP代码执行相同的命令,但是好像没有任何反应:
<?php
shell_exec('pdfcreator.exe /PF"D:\Documents\sample.docx"');
?>

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

更新

您的日志中是否有任何错误?如果将shell_exec调用包装在var_export中会发生什么?

原文

您尝试过使用system()吗?这是文档:http://www.php.net/manual/en/function.system.php。
- Eric H
我已尝试了所有系统执行命令的函数(exec、shell_exec、system、pcntl_exec、passthru). - Wern Ancheta
我不是那个给你点踩的人,非常感谢你的回答。 - Wern Ancheta
没问题,伙计。我可能应该得到-1分,但解释为什么要投反对票是好习惯。我并不认为你是那个投反对票的人。关于主题:我建议查看sixeightzero的答案。使用escapeshellcmd()可以实现Piotr Olaszewski的答案,但无需手动转义。祝你好运! - Eric H
2个回答

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

试试这个。


如果我已经在环境变量中包含了可执行文件的路径,那么我是否仍需要包含它的路径? - Wern Ancheta
我不确定,但安全是最重要的。 - Piotr Olaszewski
我遇到了语法错误,所以根据您提供的代码,我将其更改为以下内容:system('C:\Program Files\PDFCreator\pdfcreator.exe /PF"D:\Documents\sample.docx"'); 但仍然没有成功。 - Wern Ancheta

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.

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

根据您的答案尝试了下面的代码,但仍然无法工作。我弄错了什么吗: <?php $command = escapeshellcmd('pdfcreator.exe /PF"D:\Documents\sample.docx"'); `$command`; exec($command, $output); shell_exec($command); system(); ?> - Wern Ancheta
当您从CLI运行脚本时,它是否会输出任何内容?尝试类似这样的代码:$command = escapeshellcmd('pdfcreator.exe /PF"D:\Documents\sample.docx" > C:\outfile');。任何内容被写入C:\outfile吗? - Mike Mackintosh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接