【问题标题】:Using PHP to execute cmd commands使用PHP执行cmd命令
【发布时间】:2012-06-27 21:35:04
【问题描述】:

如何使用 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 中会发生什么? ### Original 你试过system() 代替吗?这是文档:php.net/manual/en/function.system.php.
  • 我已经尝试过 system 和所有其他用于在系统上执行命令的函数(exec、shell_exec、system、pcntl_exec、passthru)
  • 我不是投反对票的人,非常感谢您的回答。
  • 没问题的人。我可能应该得到-1,但这是解释为什么会发生反对票的好形式。无论如何,我不认为你是那个投反对票的人。关于主题:我会查看 Sixeightzero 的答案。使用 escapeshellcmd() 将完成 Piotr Olaszewski 的回答,但无需手动转义。祝你好运!

标签: php cmd shell-exec


【解决方案1】:
system("c:\\path\\to\\pdfcreator.exe /PF\"D:\\Documents\\sample.docx""); 

试试这个。

【讨论】:

  • 如果我已经将可执行文件的路径包含在环境变量中,是否还需要包含它?
  • 我不确定,但安全是通过所有路径。
  • 我收到一个语法错误,所以我根据您提供的代码将其更改为类似的内容:system('C:\\Program Files\\PDFCreator\\pdfcreator.exe /PF\" D:\\Documents\\sample.docx"');但仍然没有运气。
【解决方案2】:

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

【讨论】:

  • 根据您的回答尝试了以下代码,但仍然无法正常工作。我是不是搞砸了:$command;执行($命令,$输出); shell_exec($command);系统(); ?>
  • 当您从 CLI 运行脚本时,它会输出任何内容吗?尝试类似:$command = escapeshellcmd('pdfcreator.exe /PF"D:\Documents\sample.docx" &gt; C:\outfile');。是否有任何内容写入 C:\outfile?
猜你喜欢
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多