Ryan Ramsey
Ryan Ramsey

Reputation: 1

PHP Callback Process

I have a form that accesses a MySQL database and then sends an email out.

Access to the database is quick, but doing the email process is slow in comparison, which causes issues with users thinking the web page is hung while waiting for mail() to finish.

Without getting into a conversation of controlling the user behavior, is it possible to create a thread or a callback in PHP that will allow me to send the mail routine to the background so normal operation of the page can continue? Net net, is I don't want to have to wait on the process to finish and stall the page but I am willing to kick it off and check on its results later, or even click and forget it.

Yes there are alternatives by using JS but I wanted to look at options first.

Here are some caveats:
1. I don't have shell access.
2. This runs on a Windows server with no remote capability.
3. I can only create pages on my local machine and upload via ftp (ie. Godaddy)

Upvotes: 0

Views: 181

Answers (3)

Sumurai8
Sumurai8

Reputation: 20737

You can end the connection early with session_write_close(). After that you can do a time-intensive task without the user noticing that 'the page is loading'. Please note that the maximum executing time of a page still exists unless you change that. See this documentation for more information.

echo 'Hello StackOverflow';

session_write_close();

mail( $to, $subject, $message, $headers );

while( TRUE ) { }

Upvotes: 0

Segabond
Segabond

Reputation: 1143

No threads in PHP and I doubt there ever will be. You can simulate it to some extent with processes, but in your situation it is not possible. Your problem can be solved with the message queues as a typical producer/consumer problem. Create a DB table to store a queue of messages to send and have 2 scripts - first adding messages into DB. Second process is responsible for taking these messages from that DB table, sending it out and deleting it.

Instead of DB you can simply use a folder with each email represented by a file with some unique name based on microtime() call.

Upvotes: 0

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 120917

This blog post suggests setting the additional delivery mode parameter of the mail method to Background instead of the default Interactive. This might be what you are looking for.

mail($to, $subject, $message, $headers, 'O DeliveryMode=b')

Upvotes: 1

Related Questions