Trying to redirect a user before executing the beef of a script is not working

Viewed 218

I have a long running script after a user submits a form and I am trying to redirect them before the actual script starts executing

I tried to implement the accepted answer here How to cause a redirect to occur before php script finishes?

But I think the solution is outdated cause it does nothing

Here is the code at the top of the script once a form is submitted

set_time_limit(0);
header ( 'Connection: close' );
ob_start ();
header ( 'Content-Length: 0' );
header("Location: www.google.com");
ob_end_flush ();
flush ();
ignore_user_abort(true);

Expected Results: My Expected result is for the user to click the submit button and they are redirected to google.com meanwhile the script will continue to execute on my server

Actual Result: What is actually happening is the user just sits on the page till the script finishes execution

3 Answers

The safest method is to start an external application (possibly another php script with the aid of php executable) with PHP exec from your script. You can use exec($cmd . " > /dev/null &"); for background execution.

Once you send the redirect, the connection may be closed. The web server may terminate your executing PHP script, for example nginx does not support "background" commands.

the simplest way would be an ajax call but as you have mentioned that that's not working. I'll suggest you make a queue. you can create a table in the database and whenever the user submits the form add an entry to that table. and redirect the user as you wish. this won't take a long time.

now create a cron job with frequency as you please to read from that table and perform the desired script with data from the table. ones the script is done remove the entry from the table.

you can have some more details about the queue and how to create them from here

  1. You are closing the connection at 2nd line, After closing the connection, how your webserver will communicate with client??? Remove line two. or change line orders like this.

    set_time_limit(0);
    ignore_user_abort(true);
    ob_start ();
    //header ( 'Connection: close' );  //You don't need this line as you are redirecting
    header ( 'Content-Length: 0' );
    header("Location: www.google.com");
    ob_end_flush ();
    flush ();
    \*Browser will redirect at this point *\    
    ignore_user_abort(true);
    set_time_limit(0);
    \*Your Long Running Script After this line*\
    
  2. If you are redirecting to other page, you don't need to close the connection.

Related