如何从 PHP 中运行 .cmd 文件并显示结果

发布于 2024-07-27 12:45:23 字数 163 浏览 3 评论 0原文

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

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

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

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

这可行吗?

I need to run a .cmd batch file from within a php script.

The PHP will be accessed via an authenticated session within a browser.

When I run the .cmd file from the desktop of the server, it spits out some output to cmd.exe.

I'd like to route this output back to the php page.

Is this doable?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

空城旧梦 2024-08-03 12:45:23

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

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

并打印数组的内容:

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

查看此处了解更多信息

Yes it is doable. You can use

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

and print the content of the array:

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

look here for more info

夢归不見 2024-08-03 12:45:23
$result = `whatever.cmd`;
print $result; // Prints the result of running "whatever.cmd"
$result = `whatever.cmd`;
print $result; // Prints the result of running "whatever.cmd"
云醉月微眠 2024-08-03 12:45:23

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

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

I prefer to use popen for this kind of task. Especially for long-running commands, because you can fetch output line-by-line and send it to browser, so there is less chance of timeout. Here's an example:

$p = popen('script.cmd', 'r');
if ($p)
{
    while (!feof($p))
        echo gets($p);    // get output line-by-line
    pclose($p);
}
九八野马 2024-08-03 12:45:23

您可以使用 shell_exec反引号运算符,启动命令并以字符串形式获取输出。

如果您想将参数传递给该命令,您应该设想使用 escapeshellargs 来在调用命令之前逃避它们; 你也可以看看 escapeshellcmd ^^

You can use shell_exec, or the backticks operator, to launch a command and get the output as a string.

If you want to pass parameters to that command, you should envisage using escapeshellargs to escape them before calling the command ; and you might take a look at escapeshellcmd too ^^

瑶笙 2024-08-03 12:45:23

使用 php popen() 函数

Use the php popen() function

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文