how to detect user is disconnected via PHP? - 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?

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.

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).

Related

force reload/refresh a second webpage through php

I'm trying to force to reload a (second) page if a criteria is met in php
But if the criteria is met, i want the page to force reload everywhere, even if 10 people have it open at once for example.
for simplicty lets say the code is like this:
in /filelocation/script.php:
if {$data == "ok"}{
reload/refresh "reload.php" if it's open somewhere;
}
I came across a software that basicly does this, and i want to understand how this is done.
(it works cross device somehow, so i asume its done through php somehow)
Well, in your PHP code, you cannot simply reload/refresh something for all the users connected. This is simply because the PHP code is only executed when your browser requests a page on the server so it's only executed to build the HTML response and then it stops executing. Once the browser has the HTML response it will render the page and then it waits for an action from the user to do something else (such as clicking on a link or posting a form).
I imagine that you would like that when a specific user does something, like posting a comment or buying a product, you would like all the other visitors to be notified that a new comment has been posted or that the number of products available has been reduced.
To do that, you need to implement some JavaScript which is executed in the browser of each visitor. The idea is to keep a connection with the server with the help of web sockets. This way, you can inform the browser that something has changed.
You could google to find some examples of PHP apps using web sockets. The first example I found:
https://www.twilio.com/blog/create-php-websocket-server-build-real-time-even-driven-application
Another solution could be to have some JavaScript doing some pooling, meaning that every N seconds, it executes an Ajax request to the server to ask if something has changed. This can be done with the help of setTimeout(yourFunction, 10000) to call a JavaScript function every 10 seconds. This function will do the Ajax request and then update the part of your page that needs to change. Just be carefull that if you get a lot of users on your site then you'll produce quite a lot of load on your server. So this wouldn't be a good solution, but it could be an alternative to the web sockets.

How to check if visitor's IP Address is still active or online?

Is it possible to check if the visitor is still online using their IP Address?
I have already created a javascript and php to check the visitors ip address when they open one of my page using onLoad and onBeforeUnload event. But there are some cases that my script cannot detect if the visitor is still opening my site. Since onBeforeUnload is not reliable all the time.
In this case, I want to know if there are some other method to detect if the visitor is still online.
If the visitor still open the page but don't read it because may be he/she is reading other site or running other program I would still consider he/she is online.
If the visitor however, closed the browser but my script fail to detect its unload event I want to know if he/she still online.
A PHP or javascript is okay for me.
You should create JavaScript code that "pings" (sends a request, could be blank) the server via ajax. This request should in turn "mark" that user active in PHP (maybe in a database, or whatever storage method you use). You can refer to that storage of yours to see if the user is online.
Alternatively, you can use it without AJAX, however you need to do this "ping" every page request (everytime you traverse pages) in the site. In this manner, PHP "marks" the user for every page visited as long as he's logged in.
If that user was "marked" active for more than a certain threshold (like say 30 mins), consider him offline.
you DON'T need an IP address for this functionality. You just need to know that the user is still being marked as online.
If the visitor however, closed the browser but my script fail to detect its unload event I want to know if he/she still online.
That's quite impossible.
And I doubt there is any reason to do it at all.
to the best of my knowledge the most reliable way of doing it would be by using now.js for Node. You can set up a simple server, and listen for the connect and disconnect. when triggered you could send the data you need over to your php, or process it in node.

How to speed up a jquery/php/ajax chatroom?

I've created a small jquery and php chatroom with some .get and .post functions and php docs that read and write data to a sql server. It works fine, but the small problem is when someone posts something, it takes about half a second for it to appear (because of the lag).
I fear there's something wrong with my coding.
im using
setinterval (listen, 300)
as my continuous jquery function for reading new db entries, listen is a function with a .get inside. How does stackoverflow or facebook do it so that the user types something in and immediately it pops out?
Maybe try displaying the inputted chat message immediately to the user who posted it, prior to posting it to the database.
Like this:
User enters message, submits
Update users chat window so they see it immediately
POST message to database
GET from db and update all chat windows
This can be implemented using various techniques, which have many names: Long-polling, Server Sent Events, Comet, WebSockets, and others.
Basic idea is this:
Alice opens facebook. Her browser makes a request for updates ($.get, for example), but the server does not respond if there are no new updates and the request remains in 'waiting' state.
Bob opens facebook. He decides to comment on Alice's wall. His browser posts his comment to the server ($.post).
The server accepts this post, handles it properly (saves onto Alice's wall, etc)
But ALSO server checks if there is a waiting update request from Alice. If there is, server renders info about this update into response stream and closes the connection.
Alice's browser finally gets a response to this long hanging request and happily draws a red "1" in the notification area. It also immediately opens another update request (to not miss any).
Alice sees comment from Bob, which was delivered instantly.
The technique described is called "long polling" and it was first introduced by Google in Gmail.
You can use HTML5 sockets, however these are very much in their infancy and not widely supported (i.e. by IE).
Lots of systems use Flash as a middle-man as that can hold a connection open.
With either of these you can use your PHP code that stores the comment to the database to also push this out to every "listener". This will be the quickest way possible. If your system is super clever it'll incorporate all three - HTML5 sockets where it can, Flash where it can't, and your regular polling were there's no Flash either.
http://pusher.com/ might be a good starting point for further learning.
Most sites that have fast chat use a technique called comet. You can read more about it here: http://ajaxian.com/archives/comet-a-new-approach-to-ajax-applications
It essentially is a piece of modified server software that waits to return a response to the user until either a message is sent or it is about to timeout.

How to stop the 1st ajax request if it is called again before the first call gets a response?

There might be some cases that your request takes long time because
of some problems with your client internet connection or your server
connection. So since the client doesn't want to wait he clicks on the Ajax
link again which sends the request to the server again which messes up
the following:
Rendering of our website in the browser because we are giving extra
load to the browser.
What if the second request processed correctly and you showed user
the page and then comes along the error message from your first
request(saying request timed out) which loads above on the correct
content and mess up with the user reading the correct content.
I want to stop the 1st Ajax response if the Ajax function is called twice. How do I do this?
so i want to stop the 1st Ajax response if the Ajax function is called
twice
What you actually want is to prevent a second request when a first request is in progress.
For example, You may have to change the Save button to Saving..., disable it (and add a little progress wheel) to give live feedback to the user. (Facebook does this)
The key is love feedback to the user. If the user is clueless on what is going on, they are going to think nothing is happening.
You might want to check why the operation is taking long
If this is a complex/time consuming operation, like, say a report generation or a file upload, a progress bar should do
If this is because of the client's internet connection, say it up front, like Gmail: Your have a slow Internet connection and this site may be slow. Better still, provide a fallback option, with less/no Ajax.
You say cause we are giving extra load to the browser: this is kind of fishy. You will not be giving extra load to the browser unless you are giving it tons of HTML to render. Use Ajax only for small updates on the browser. You may want to reload the page if you expect a large change.
How bout seeing as your using some form of JavaScript to begin with you have that link either hidden or disabled in a manor of speaking til the pages request has been followed through with. You could for example have the requested ajax wait for a second variable that would enable that link so a user could click it. But until that variable is received from the original AJAX request its disabled to the click, then if it is clicked it disables again and waits for the same variable to come back again.
Think of how some developers disable a submit button on a form so a user can't double submit there form.. same concept of notion here.

Force users to logout when they leave my php website?

In my php application, I'm using $_SESSION to track whether a user is logged in. If a user leaves any page on my site at http://mysite.com and goes to http://someotherwebsite.com, I want to automatically log them out, such that if they return to any page on http://mysite.com, they need to login again.
Is there an easy way to do this?
You cannot explicitly tell when an user leaves your site, your best bet would to be to implement a timeout on your sessions.
As most of the answers have said, you could check with the JavaScript event onbeforeunload but the user can by-pass this by disabling JavaScript or, as BalusC had pointed out, using a web browser that does not support it, such as Opera.
Therefore, I strongly believe implementing a timeout on your sessions is the best way to force a logout.
You could perform an AJAX call in the onbeforeunload event to some server side script that will kill the session.
Except for putting a timeout on your sessions - not really. The only way that comes to mind is the onbeforeunload JavaScript event that fires when the user leaves the current page, but that event doesn't know where the user is going. You could however, if you really want to do this, maybe build something based on the following hacky workaround (untested):
set an onbeforeunload event that sends an AJAX call to your server. (How to do this successfully - so the call gets through before the page gets closed - is an issue of its own, a search for "onbeforeunload ajax" on SO should yield some results.
The Ajax call would start a countdown saying that this user's session is about to die in, say, fifteen seconds.
If the user is leaving your site, the countdown applies.
If the user is going to a different page on your site, you clear any "die" countdowns when serving the next page.
This is likely to be shaky because it could happen that an Ajax request starting a countdown arrives at the server after the next page has already eliminated that countdown. But if you really need to do this, this may be a direction. Works for users with JS enabled only, of course.
A second idea how to implement this would be to put an extremely low timeout on sessions (e.g. 90 seconds), and to put an iframe on every page you serve. That iframe would then make a call to the page every 60 seconds.
This would work without JavaScript, but could create annoying clicking noises in older versions of Internet Explorer (I don't know whether that stopped in 6 or 7?)
You can't (but your sessions will time out automatically after a while ; so you could set the timeout to a short time).
From what I know about PHP (which isn't much) would your application ever know they left the site? If you go to someotherwebsite.com, your code isn't called again until they return.
Unfortunately Not Really,
This is one of the big problems with web applications. Your applications has no way of knowing that the browser has moved on to a different website.
As ChristohpeD mentions you can set the session timeout.
Just remember that your site will only refresh the time when the server recieves a post or some kind of javascript ping.
Hope That Helps

Categories