简体   繁体   中英

PHP exec and header redirect

I have a long running PHP script that i want to be executed in background on server after a user action. and the user should be redirected to other page while command should be running in background. Below is the code

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

The above script is running fine, but page does not redirected until $command = exec('php -q /mylongrunningscript.php'); is executed.

I want that user should be immediately redirected to the welcome page.

Is there any other way to achieve this task. The other idea is that that $command = exec('php -q /mylongrunningscript.php'); should be executed on welcome page, but welcome page HTML is shown after the command has executed. command takes about 5,6 minutes and this time page does not redirects.

I am On Cent os Linux with PHP 5.3

Can you try this instead:

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

PS: Note that this is redirecting stdout and stderr to /dev/null If you want to capture output then use:

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

Alternatively use this PHP function to run any Unix command in background:

//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);
}

Courtesy: A comment posted on http://php.net/manual/en/function.shell-exec.php

As noted in the exec() manual page of PHP:

If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends.

So let's do that, using 2>&1 (basically 2 is stderr and 1 is stdout , so what this means is " redirect all stderr messages to stdout "):

shell_exec('php -q /mylongrunningscript.php 2>&1');

or if you want to know what it outputs:

shell_exec('php -q /mylongrunningscript.php 2>&1 > output.log');

将脚本输出发送到/ dev / null,然后exec函数将立即返回

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM