Alireza
Alireza

Reputation: 6848

how to detect user is disconnected via PHP?

Is there a way to detect whether a user is disconnected from internet or not? The way that stackoverflow does when you want to post a question. I couldn't think of any approach to do that. Could someone shed some light on the subject?

Upvotes: 2

Views: 2305

Answers (2)

Whisperity
Whisperity

Reputation: 3042

I guess Stack Overflow uses AJAX, which is a JavaScript driven program executed on the client side inside your browser. This ajax setup is responsible for notifying the user when, for example, a new answer is posted, and giving them the opportunity to load said new answer without reloading the whole page.

And this construct has a way to detect errors in the communication with the server which it is interpreted as the user being disconnected, resulting in a warning.

However, this requires that the user is still having the browser open. There are also various other functions in JavaScript and AJAX to execute something when the user is closing the page, but neither of them are considered to always work. There are no silver bullets after all.

From the server's side, one can monitor the constant ping-pong of the user client's AJAX and execute something when this ping is fading away. Like: the user has been pinging us in every 5 second in the past two minutes, but now this ping is missing.

The main problem with this lies inside the principles of PHP and that every pages basically lives on its own. When the request is get, the page is loaded and created, but at the end of request, the current page instance is denied from existance, just like how every variable is lost which is not saved elsewhere (cookie, session, database).

Upvotes: 3

Daniil Ryzhkov
Daniil Ryzhkov

Reputation: 7596

You can send AJAX-request to PHP script when windows is closed:

window.onbeforeunload = function(){
    // Request goes here
}

Alternativly you can use websocket-technology (you can use phpDaemon) to connect with server permanently so you will know when user is disconnected from internet or your site or pereodicly (use setInterval function) ping your server.

Upvotes: 5

Related Questions