Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cause a redirect to occur before php script finishes?

I want to run a php script that will send out a bunch of emails (newsletters) but since it can take a while for that to run I want the user be immediately redirected to a page with a message like "Your newsletters are queued to be sent out."
So far the header redirects work but they do not cause the redirection until after all the emails get sent. Can I close the connection after sending the redirect so the browser acts on the redirect immediately? I tried stuff like this


ob_start();
ignore_user_abort(true);
header( "refresh:1;url=waitforit.php?msg=Newsletters queued up, will send soon.");
header("Connection: close");
header("Content-Length: " . mb_strlen($resp));
echo $resp;
//@ob_end_clean();
ob_end_flush();
flush();

in various permutations and combinations but to no avail. I suspect it cannot be done so simply but before I start messing with cron jobs or custom daemons I thought I'd look into this approach. Thanks

eg like blockhead suggests below, but no luck

ob_start();
ignore_user_abort(true);
header( "refresh:1;url=mailing_done.php?msg=Newsletters queued for sending.");
header("Connection: close");
header("Content-Length: 0" );
//echo $resp;
ob_end_flush();
flush(); 
like image 480
lost baby Avatar asked May 08 '12 18:05

lost baby


2 Answers

I would try this:

<?php
header("Location: waitforit.php?msg=Newsletters queued up, will send soon.");
header("Content-Length: 0");
header("Connection: close");
flush();
//Do work here
?>
like image 152
Phil W Avatar answered Jan 01 '23 10:01

Phil W


If you want to run script continuously and still want to display some output then, why don't you use an ajax request to server which can queue mails and still let user continue browsing that page.

If you don't want to use this; instead you could use, the script runs background even if the user will be redirected to show_usermessage.php page

<?PHP
    //Redirect to another file that shows that mail queued
    header("Location: show_usermessage.php");

    //Erase the output buffer
    ob_end_clean();

    //Tell the browser that the connection's closed
    header("Connection: close");

    //Ignore the user's abort (which we caused with the redirect).
    ignore_user_abort(true);
    //Extend time limit to 30 minutes
    set_time_limit(1800);
    //Extend memory limit to 10MB
    ini_set("memory_limit","10M");
    //Start output buffering again
    ob_start();

    //Tell the browser we're serious... there's really
    //nothing else to receive from this page.
    header("Content-Length: 0");

    //Send the output buffer and turn output buffering off.
    ob_end_flush();
    flush();
    //Close the session.
    session_write_close();


    //Do some of your work, like the queue can be ran here,
    //.......
    //.......
?>
like image 24
Bhavesh G Avatar answered Jan 01 '23 11:01

Bhavesh G