PHP 执行和 header 重定向

标签 php linux exec

我有一个长时间运行的 PHP 脚本,我想在用户操作后在服务器后台执行。并且用户应该被重定向到其他页面,而命令应该在后台运行。 下面是代码

$command = exec('php -q /mylongrunningscript.php');
header("Location: /main.php?action=welcome");

上面的脚本运行正常,但页面不会重定向,直到 $command = exec('php -q/mylongrunningscript.php'); 被执行。

我希望该用户立即被重定向到欢迎页面。

有没有其他方法可以完成这个任务。 另一个想法是 $command = exec('php -q/mylongrunningscript.php');应该在欢迎页面上执行,但欢迎页面 HTML 在命令执行后显示。命令大约需要 5.6 分钟,此时页面不会重定向。

我在 Cent os Linux 上使用 PHP 5.3

最佳答案

你能试试这个吗:

$result = shell_exec('php -q /mylongrunningscript.php > /dev/null 2>&1 &');

PS:请注意,这是将 stdout 和 stderr 重定向到 /dev/null 如果您想捕获输出,请使用:

$result = shell_exec('php -q /mylongrunningscript.php > /tmp/script.our 2>&1 &');

或者使用此 PHP 函数在后台运行任何 Unix 命令:

//Run linux command in background and return the PID created by the OS
function run_in_background($Command, $Priority = 0) {
    if($Priority)
        $PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
    else
        $PID = shell_exec("nohup $Command > /dev/null & echo $!");
    return($PID);
}

礼貌:发表在 http://php.net/manual/en/function.shell-exec.php 上的评论

关于PHP 执行和 header 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14119628/

相关文章:

php - Opencart product.tpl 未更新

php - 将收到的数据保存到 Woocommerce 3 中来自外部交付服务的订单

javascript - 将 var 传递给另一个页面

c - 无法在 unix 中读取/proc/[pid]/stat 显示段错误

linux - FPGA与PC以太网连接

php - 如何在 PHP 中执行 Imagemagick

php - 空查询验证的更好实践

linux shell 命令 mv 许多文件

php - 如何使用 PHP exec() 获取正在运行的 php 脚本列表?

javascript - 如何给用coffeebar编译的文件下命令