调用php并立即返回

时间:2014-03-06 08:06:50

标签: php html web

我必须打电话给php" build.php"从一个按钮动作,php将调用一个python脚本,并应立即返回。

行动:

<form method="get" action="build.php">
    <input type="hidden" name="branch" value="master">
    <input type="submit" value="Build Master" id="btnMaster">
</form>

build.php

<?php
    if(isset($_GET['branch']))
    {
        $output = shell_exec('/usr/bin/python /Users/testuser/gitroot/buildOnGuest.py --dest /Users/testuser/Builds --branch ' . $_GET['branch'] . '  2>&1 &');
    }
    elseif (isset($_GET['tag']))
    {
        $output = shell_exec('/usr/bin/python /Users/testuser/gitroot/buildOnGuest.py --dest /Users/testuser/Builds --tag ' . $_GET['tag'] . '  2>&1 &');
    }
?>

因此python脚本在后台执行(&amp;),php应立即返回主页面。它有可能吗?如何?

4 个答案:

答案 0 :(得分:2)

如果您只想通过PHP重定向,请在header('Location: /path/to/index.php');子句后添加if,它将返回!!!

逻辑上,这应该是这样的:

<?php
    if(isset($_GET['branch']))
    {
        $output = shell_exec('/usr/bin/python /Users/testuser/gitroot/buildOnGuest.py --dest /Users/testuser/Builds --branch ' . $_GET['branch'] . '  2>&1 &');
    }
    elseif (isset($_GET['tag']))
    {
        $output = shell_exec('/usr/bin/python /Users/testuser/gitroot/buildOnGuest.py --dest /Users/testuser/Builds --tag ' . $_GET['tag'] . '  2>&1 &');
    }

    /* add here, appending $output value for better understanding */
    header('Location: /path/to/index.php?status=$output'); 
?>

答案 1 :(得分:1)

尝试将输出重定向到/dev/null我们做了几乎完全相同的事情,这对你正在尝试做的事情非常有效。

<?php
    if(isset($_GET['branch']))
    {
        $output = shell_exec('/usr/bin/python /Users/testuser/gitroot/buildOnGuest.py --dest /Users/testuser/Builds --branch ' . $_GET['branch'] . ' > /dev/null 2>/dev/null &');
    }
    elseif (isset($_GET['tag']))
    {
        $output = shell_exec('/usr/bin/python /Users/testuser/gitroot/buildOnGuest.py --dest /Users/testuser/Builds --tag ' . $_GET['tag'] . ' > /dev/null 2>/dev/null &');
    }
?>

答案 2 :(得分:0)

set_time_limit(0);
ignore_user_abort(true);
header("Connection: close\r\n");
header("Content-Encoding: none\r\n");  
ob_start();          
echo json_encode($response);
$size = ob_get_length();   
header("Content-Length: $size",TRUE);  
ob_end_flush();
ob_flush();
flush();
session_write_close();

$ response是您要发送回调用脚本的响应。在session_write_close()之后执行任何操作,以便这些操作不会进一步阻止执行调用脚本

答案 3 :(得分:0)

如果我的其他答案不起作用,您可以尝试:

最快/最简单的方法可能是使用JavaScript在iFrame中加载脚本。这将加载它而不导航离开页面。

您的信息页:

<form method="get" action="build.php">
    <input type="hidden" name="branch" value="master">
    <input onclick="runBuild()" type="submit" value="Build Master" id="btnMaster">
</form>

<iframe id="launch_script" name="launch_script" style="display:none"></iframe>

function runBuild(){
    document.getElementById('launch_script').src = 'build.php';
}

请注意,您可能需要将您的GET参数与iFrame src一起传递。