2012-06-26 124 views
5

如何在命令行中使用php正确执行命令?比如我使用下面的命令在命令行到的docx文件转换成PDF文件:使用PHP来执行cmd命令

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

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

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

这是PHP的可能吗?如果是的话,我该怎么做呢?

+0

###更新在日志中是否有错误?如果将'shell_exec'调用包装在'var_export'中会发生什么? ###原文你是否尝试过'system()'而不是?这里是文档:http://www.php.net/manual/en/function.system.php。 –

+0

我试过系统和所有其他功能在系统上执行命令(exec,shell_exec,system,pcntl_exec,passthru) –

+0

我不是那个downvoted的人,你的回答非常感谢。 –

回答

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

试试这个。

+0

如果我已经将它包含在环境变量中,是否还需要包含可执行文件的路径? –

+0

我并不确定,但安全是通过所有路径。 –

+0

我得到一个语法错误,所以我根据您提供的代码将其更改为如下所示:system('C:\\ Program Files \\ PDFCreator \\ pdfcreator.exe/PF \“D:\\ Documents \\ sample.docx“'); 但仍然没有运气。 –

4

不要忘了用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变量中。如果不是,请包含该命令的完整路径。

+0

根据您的答案尝试了下面的代码,但仍然无效。我搞砸了: <?php $ command = escapeshellcmd('pdfcreator.exe /PF"D:\Documents\sample.docx“'); '$ command'; exec($ command,$ output); shell_exec($ command); system(); ?> –

+0

当你从CLI运行脚本时,它输出什么东西?尝试如下所示:'$ command = escapeshellcmd('pdfcreator.exe /PF"D:\Documents\sample.docx“> C:\ outfile');'。什么都可以写成C:\ outfile? –