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);
在這里查看更多信息
#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()函數