2

Is there a way to make PHP request where user doesn't have to wait for response? Some sort of "php request in background"?

For example, if application needs to send 100 emails because the user had submitted something, I don't want to show "sending... please wait" for this user, but I want some other script to do the job independent from that user...

domagojk
  • 1,020
  • 2
  • 11
  • 25
  • google for "asynchronous PHP", and check http://stackoverflow.com/questions/124462/asynchronous-php-calls – dkretz Jul 21 '11 at 19:56

5 Answers5

7

Options:

  1. Stick in a db (or a file) and use a cron to poll it (easiest as you probably already use a db).
  2. Use something like RabbitMQ or ØMQ (my favourite)
  3. Spawn a separate process to do it using fork/exec (would not recommend that).
  4. As others have suggested - fake it by using an Ajax request. Viable - but I find it ugly.
Emil Ivanov
  • 37,300
  • 12
  • 75
  • 90
3

You can maybe send the request in Ajax this way to UI won't freeze and the task will be executed on the server?

Patrick Desjardins
  • 136,852
  • 88
  • 292
  • 341
  • What if user leaves the page in the meantime? Will the script be executed anyway? – domagojk Jul 21 '11 at 19:52
  • @domagoj412 - Yes. If the request got to the web server, it will work. The user will just not get the response. – Emil Ivanov Jul 21 '11 at 19:56
  • Like Emil say, if the request went to the server, whatever the client do the server won't stop but the client won't receive the notification of any text from the server. Should do the job and won't require you to configure other Queue messaging system. – Patrick Desjardins Jul 21 '11 at 20:02
1

You could send the request via ajax and then redirect the user elsewhere upon success. The server script will still process, but no confirmation will be given to the user.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
0
exec('php script.php > /dev/null & echo $!', $o);

You may want to use php-cli instead of php as well. The command above returns the process id of the background script in $o[0] so you can set something up to poll it with ajax or somethig if you want to show the user it's progress.

Paul
  • 139,544
  • 27
  • 275
  • 264
0

Create a php routine to do the actual work of sending the emails and call it via http GET using the technique described here.

Community
  • 1
  • 1
Jonathan M
  • 17,145
  • 9
  • 58
  • 91