Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting Browser exit in PHP

Tags:

browser

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

like image 885
Woz Avatar asked Nov 29 '22 17:11

Woz


2 Answers

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 (e.g. using cron) whose sessions have not been active (i.e. who haven't sent a "keepalive") for more than X minutes.

like image 23
CodeCaster Avatar answered Dec 04 '22 11:12

CodeCaster


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.

like image 161
Taha Paksu Avatar answered Dec 04 '22 11:12

Taha Paksu