在后台执行php中的.bat文件

时间:2015-01-13 14:16:09

标签: php windows batch-file background cmd

我尝试在后台从php执行.bat文件(带有xampp的Windows Server)。点击按钮后,它也应该转到另一个网站。 但是当我点击按钮时,浏览器正在等待脚本完成。大部分都是以超时结束。

我的PHP代码:

if (isset($_POST['test']))
{
    exec('C:\Daten\test.bat');
    header("Location:test_status.php");
}

我怎么能告诉php exec,不要等待?

我也试过跟随,但不起作用:

exec('C:\Daten\test.bat' . '> /dev/null &');

3 个答案:

答案 0 :(得分:2)

感谢您的回复,但这对我不起作用。我在互联网上发现了许多解决方案的想法,但没有任何对我有用。

现在我终于找到了解决方案! 关键字是popen!这很好用:

$handle = popen ('start /B C:\Data\restart_TS3.bat > C:\Daten\restart_TS3.log 2>&1', 'r');
pclose ($handle);
header("Location:ts3_status.php");

这样做如下: popen打开一个启动批处理文件的后台进程,输出转到日志文件。 然后你需要用pclose关闭它。 (批处理仍在后台运行) 之后,它会打开另一个网站,在我看来是一个“查看当前状态”的网站。

如果您不想要日志,您还可以使用> nul输出(如MarkB之前所述)。这看起来像是:

$handle = popen ('start /B C:\Data\restart_TS3.bat >nul 2>&1', 'r');

小心路径中的空白区域! 我不知道为什么,但这不起作用:'start / B“C:\ Data Folder \ restart_TS3.bat”> nul 2>& 1' 在这种情况下,你需要“在这样的文件夹中:

$handle = popen ('start /B C:\"Data Folder"\restart_TS3.bat >nul 2>&1', 'r');

这适用于文件夹名称中的空白区域。

答案 1 :(得分:1)

您正在使用Windows。 Windows中没有/dev/null(它只是nul),并且没有&在后​​台运行作业。 cmd.exe中的&是命令分隔符。所以你的exec()会挂起/等待.bat完成。

尝试

exec('start c:\daten\test.bat');
而是,它将批处理文件作为一个单独的进程启动。

答案 2 :(得分:1)

这对我有用。

exec("start cmd /c test.bat", $output);
var_dump($output);