【问题标题】:How to run a .cmd file from within PHP and display the results如何在 PHP 中运行 .cmd 文件并显示结果
【发布时间】:2010-11-11 21:42:47
【问题描述】:

我需要在 php 脚本中运行 .cmd 批处理文件。

将通过浏览器中的经过身份验证的会话访问 PHP。

当我从服务器桌面运行 .cmd 文件时,它会向 cmd.exe 输出一些输出。

我想将此输出路由回 php 页面。

这可行吗?

【问题讨论】:

  • [再次添加评论,因为链接被破坏] 不会将 .cmd 文件包含在反引号中,就像这里的 .bat 文件示例一样? php.net/manual/pl/language.operators.execution.php
  • 这样的?我现在手头没有 PHP,所以无法测试,抱歉! $test"; ?>
  • @hamlin11 - 什么不起作用(“print ls;”)?我刚刚测试了它(不过在 linux 机器上),它对我来说效果很好。试试:
  • 只是好奇,cmd文件是做什么的?
  • 运行 7zip 并做一些文件管理工作

标签: php batch-file cmd windows-server-2003


【解决方案1】:

是的,这是可行的。你可以使用

exec("mycommand.cmd", &$outputArray);

并打印数组的内容:

echo implode("\n", $outputArray);

look here for more info

【讨论】:

    【解决方案2】:
    $result = `whatever.cmd`;
    print $result; // Prints the result of running "whatever.cmd"
    

    【讨论】:

      【解决方案3】:

      您可以使用shell_exec 或backticks operator 来启动命令并将输出作为字符串获取。

      如果你想向该命令传递参数,你应该设想在调用命令之前使用escapeshellargs 来转义它们;你也可以看看escapeshellcmd ^^

      【讨论】:

        【解决方案4】:

        使用 php popen() 函数

        【讨论】:

          【解决方案5】:

          我更喜欢使用popen 来完成此类任务。特别是对于长时间运行的命令,因为您可以逐行获取输出并将其发送到浏览器,因此超时的可能性较小。这是一个例子:

          $p = popen('script.cmd', 'r');
          if ($p)
          {
              while (!feof($p))
                  echo gets($p);    // get output line-by-line
              pclose($p);
          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2012-12-31
            • 1970-01-01
            • 1970-01-01
            • 2018-04-27
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多