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

时间:2021-07-31 02:29:54

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

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

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

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

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

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

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

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

Is this doable?

这可行吗?

5 个解决方案

#1


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

在这里查看更多信息

#2


$result = `whatever.cmd`;
print $result; // Prints the result of running "whatever.cmd"

#3


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:

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

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

#4


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

您可以使用shell_exec或反引号运算符来启动命令并将输出作为字符串。

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 ^^

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

#5


Use the php popen() function

使用php popen()函数

#1


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

在这里查看更多信息

#2


$result = `whatever.cmd`;
print $result; // Prints the result of running "whatever.cmd"

#3


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:

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

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

#4


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

您可以使用shell_exec或反引号运算符来启动命令并将输出作为字符串。

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 ^^

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

#5


Use the php popen() function

使用php popen()函数