我有一个长时间运行的 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/