Let's say a user submits a form to submit.php, the server will return two possible responses: A or B. If the server is going to return B, then I'd like the server to send an email to an address.

<?php
     if(B){
          echo 'B';
     }
     mail($to, $subj, $msg);
?>

The problem is that it often takes some time to wait mail() to finish... the user can only get responses after the server finishes mail(). This is a very bad experience for my users.

Is there any way that the server can return response 'B' to the user immediately, then it sends mail?

有帮助吗?

解决方案 2

You can use a task queueing platform to execute asynchronous tasks, it shouldn't be so complicated to setup, something like ActiveMQ

其他提示

Take a look at the flush() function

Flushes the write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats. flush() may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means you will have to call both ob_flush() and flush() to flush the ob output buffers if you are using those.

Change the code to the following:

if (B) {
    echo 'B';
    flush();
    ob_flush();
}

However, it should be noted that many things could prevent this from working (as quoted from the flush() documentation):

Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser.

Server modules for Apache like mod_gzip may do buffering of their own that will cause flush() to not result in data being sent immediately to the client.

Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen.

Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page.

Use this PHP functionality register_shutdown_function

<?php
  if(B){
    echo 'B';
  }
  $m = "mail($to, $subj, $msg);";
  register_shutdown_function(create_function('',$m));
?> 

register_shutdown_function: Register a function for execution on shutdown

the trick is to use create_function() to create a "function" that calls the desired function with static parameters.

more about create_function()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top