I'm trying to write a simple web chat app with PHP and AJAX.
I need to be aware of all the open sessions so that I can display a list of online users that are available to talk to. I also need to be aware of log outs because I use "both the sending and the receiving party are offline" as a condition for considering a chat session terminated and deleting the messages.
I'm keeping track of logged in users in a database: adding an entry on log-in and removing it on log-out works fine, but it's not comprehensive, as there are two other ways a user can become logged out:
Simplest solution seems to be keeping a timestamp of last activity. I see some problems with this though:
Any help appreciated. I'm coding this myself because I'm not aware of any web chat frameworks that can integrate with my existing user database, do correct me if I'm wrong.
The register. php page asks for the desired username, email, and password of the user, and then sends the entered data into the database, once the submit button is clicked. After this, the user is redirected to the index. php page where a welcome message and the username of the logged-in user is displayed.
php session_start(); if($_SESSION['logged']==true){ echo $_SESSION["username"]; echo '<a href="logout. php"><span>Logout</span></a></li>'; } elseif($_SESSION['logged']==false) echo '<a href="registerform. html"><span>Login/Register</span></a></li>'; ?>
You should change this to: $_SESSION['username'] = $myusername; $_SESSION['password'] = $mypassword; Because $myusername and $mypassword refer to the username and password sent to the script from the form data. Thank you so much, can not believe i missed that -_-
I don't think you're going to be able to do much to mitigate the constant querying to determine if users have logged off by closing the browser, internet connection issues, etc., but you could perhaps have each client make an AJAX request to the server every 5 seconds to update the last activity time, and have your application on the server consider the user "logged off" if they have missed 3-4 consecutive requests (ie, their last activity time is > 20 seconds).
On the client side, you could then check the last activity time every time your client sends a message to another user, and respond that they'd logged off if that had happened. If they attemped to open a chat with another user, you could also do an immediate call to check their status. Then you could perhaps check the status of all users in the user list every 30 seconds. That way your client gets pretty quick feedback if the person (s)he is chatting with drops offline unexpectedly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With