简体   繁体   中英

PHP - Execute expensive code after sending HTTP Redirect Headers

I am VERY new to PHP, I'm currently working on a service, part which includes short urls, I have everything set up ok using header redirection:

<?php

if (code_exists($code)) {
    // this code gets url for redirect:
    $url_query = mysql_query("SELECT * FROM urls WHERE code = '".$code."'");
    $url = mysql_result($url_query,0,'url');
    $id = mysql_result($url_query,0,'url_id');

    // this code redirects user
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Thu, 1 Jan 1970 00:00:00 GMT");
    header( "HTTP/1.1 301 Moved Permanently" );
    header( "Location: ".$url );

    // this code executes a function, takes 3 - 4 seconds to return
    $affected = dostuff($id);

} else {
    echo "Code Error: ".$code;
}

?>

The line $affected = dostuff($id); is calling several external API's and writing the results to a mysql table (often 100+ rows).

The problem is because the external API's and adding rows takes several seconds, the user has to wait for this before being redirected meaning a bad user experience.

Is there any way that I can build and SEND the headers to the user without the code execution being halted?

Alternatively is there a way to 'kick off' another script but pass it the $id parameter?

I would rather avoid using CRON jobs if possible as these confuse the hell out of me :).

Any help greatly appreciated.

There is a write-up on this available here: https://www.zulius.com/how-to/close-browser-connection-continue-execution/

In short, you need to send headers to tell the browser to close connection, force the HTTP server to send data to the browser, and prevent PHP from timing the script out.

The downside of this method is that one of your HTTP worker threads is used up serving this request. With enough requests, you could easily run out of worker threads to be able to serve requests. Another way to look at this is if someone wants to attack your server, calling the URL to kick off this process many times as fast as possible will quickly bring your server to its knees.

I think you need to create worker threads executes the function and on completion updates the status on your database or fires an email to the user. And the user can comeback to a status screen after that.

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