简体   繁体   中英

Detecting Browser exit in PHP

I have looked at a few topics (here & google) regarding detecting browser exit in php and im not really any clearer on how to do so.

I tried the register_shutdown_function in PHP but that was executing even when i refreshed the browser page.

Can anyone help?

Thanks in advance

PHP is a server side language. Browser events are handled by DOM events. On "onunload" or "onbeforeunload" events, sending an AJAX call to a PHP file.

And in this other question there is a flavored explanation of what I'm saying.

I don't think there is any foolproof way to detect a browser close button in PHP or Javascript.

It is much safer and better to handle it via timer based polling OR just simple session timeouts on server side.

Please explain what you want to do when the browser closes, to see if there perhaps is another way to do so.

A web server sends its response to the browser, and then (usually) closes the connection. You'd have to do something in Javascript, but that won't catch all conditions. You certainly can't detect it serverside.

It can be detected using the Javascript onbeforeunload or onunload functions, but that is absolutely not accurately, since it won't detect:

  • a browser crash
  • a browser exit
  • a computer shutdown
  • a link click on the page
  • when going Back in the browser

Also see this answer .

So for example when you want to log out users when they close the browser, you'd better use a "keepalive" mechanism instead of a "say goodbye" one. You can then log those users off on the server (eg using cron ) whose sessions have not been active (ie who haven't sent a "keepalive") for more than X minutes.

One solution that is at least fool resistant is to send a heartbeat to the server using Javascript and Ajax, then assuming that the browser window has been closed when the signal stops pulsing.

Another would be to use web sockets to maintain a constant connection until the browser window closes.

In any case it would take quite a bit of work from your part to set it up

Not just with PHP.

PHP runs server-side, and is far done processing your page by the time the user will have a chance to close their browser. You could technically detect if PHP was still processing the page and the user closes it, with a specific configuration. However, it is not ideal. See connection_aborted() .

What you need to do is set up a long-polling connection with JavaScript, and monitor it server-side. You will then get an idea for when that window is closed. That connection could be made to your PHP script, allowing PHP to check connection_aborted() . Note that you will need to set up ignore_user_abort() for this to work, or configure PHP.ini accordingly.

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