David G
David G

Reputation: 337

Delay in PHP mail() function

I have a small ordering taking app which submits the order to a PHP script by ajax. When the PHP script receives the order it places it in a database, sends an 'OK' message back to the client and then sends a confirmation email to the customer and another to me. The problem is that the client is not seeing the 'OK' (which updates the browser display) for about 15 seconds. If I comment out the email sends, no delay.

... write to database
echo "OK";
mail($semail,'Msg Subject',$message, $header, $bounceto);
mail($semail2,'Msg Subject',$mesage, $header, $bounceto);

Message is only a couple of lines.

Questions:

Upvotes: 3

Views: 4973

Answers (2)

rubo77
rubo77

Reputation: 20817

It should work with fastcgi-finish-request.php but it requires PHP FPM

Adding this will output the buffer to the user and cut the connection, the rest of the script will still be executed, but no additional output will be sent, so be sure to output everything before you call fastcgi_finish_request() and thereafter the mail() function

Upvotes: 0

Mark
Mark

Reputation: 1417

That's because http://php.net/manual/en/function.mail.php returns boolean value for success or failure and your mail server takes time to process email request.

You can implement some kind of MYSQL queue for emails where you would put emails to be sent and check it with background task (for example using CRON to lauch YourMailQueueProcessingScripts.php that will check if there are any emails to send and perform the sending operation - have in mind that you can run CRON once per minute at most and I don't know if 1 minute delay of sending email is acceptable by you)

Upvotes: 3

Related Questions