简体   繁体   中英

redirect but still continue to process exec()

This code example is supposed to redirect and continue processing a long operation, however it doesn't redirect until after the exec command is complete. I've tried multiple other ways of doing this and nothing works. Where am I going wrong?

ignore_user_abort() is enabled in my php.ini

<?php
set_time_limit ( 0 );
header ( 'Connection: close' );
ob_start ();
header ( 'Content-Length: 0' );
header ( 'Location: /redirect.php' );
ob_end_flush ();
flush ();
ignore_user_abort ( true );

exec('command that takes 5 minutes to process');
exit ();
?>

I appreciate the help in advance.

I recently had to write a webhook handler that was supposed to return a "200 OK" response immediately before continuing to process other long running tasks.

I have observed that the process of hanging up immediately was never possible when I the entire process was happening using the same web server. So if the client IP of connection where you need to send a response is the same as the server IP, you might never be able to do it. But it always worked when the incoming connected was a real world remote client.

With all that said, I was just returning a "200 OK" response. Which should not be different than sending back a redirection.

The code that worked for me was ...

public function respondASAP($responseCode = 200)
{
    // check if fastcgi_finish_request is callable
    if (is_callable('fastcgi_finish_request')) {
        /*
         * This works in Nginx but the next approach not
         */
        session_write_close();
        fastcgi_finish_request();

        return;
    }

    ignore_user_abort(true);

    ob_start();
    http_response_code($responseCode);
    header('Content-Encoding: none');
    header('Content-Length: '.ob_get_length());
    header('Connection: close');

    ob_end_flush();
    ob_flush();
    flush();
}

You could adapt it to your situation and make it set a redirection header instead of an "200 OK".

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