简体   繁体   中英

stopping a php background process

I have a page where the user can start a background process. I'd like to stop this process in case the user refreshes the page or closes the tab or browser. Tried connection_abort() but no luck, the script just goes on running. Any ideas?

I think you are out of luck. http is a stateless protocol, as soon as your page is served the connection is closed.

Besides some ajax tricks, there is no way to tell that the user refreshes or closes the browser.

If you have a unique identifier for the user, and this can be tied or stored along with the process id, the following logic could work:

  1. User requests page
  2. User is given a unique id
  3. The background process is started and it's id is logged to a database along with the user id
  4. The process keeps checking the database - at a chosen frequency - for it's record in the database, if it doesn't exist or isn't as expected the process stops itself.
  5. Then whatever front-end you have for the user could either:
    • Trigger a script (ie stop_process.php?user=id) via ajax when it needs to - ie when the page navigates away. This approach can be unreliable due to onbeforeunload preventing or stopping ajax requests in certain browsers.
    • Have an ajax polling script that keeps updating the process record in the db with a timestamp, if this stamp gets out of date - meaning the user has navigated away or stopped js - then the process stops.

The above is a rather involved solution (and possibly temperamental as it relies on JavaScript) so probably should only be considered if really required or if the target audience can be locked down.

As a non js solution you could rely on the polling method and set-up a meta-refresh frame. However this might send users of older versions of Internet Explorer mad for the constant 'clicking'. Not to mention the solution being rather inelegant.

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