2012-06-26 130 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? –