Online Listing problem - Chat in php - php

I have to identify the online users
The condition is when a user close the window, he/she will be removed automatically from online list.
the List is being generated on the base of session value.
any one please help me.........

its difficult to store a flag on the close window event. what if the user closes the browser of shuts down the system directly?
you can achieve approximately the same thing by storing a unix timestamp in the database every time the user does some activity (also including page refreshes ).
The to see whether the user is online, add a certain amount to time to this timestamp and compare the value with current time stamp.
For eg. lets say we decide to consider a user online if there is some activity in past 10 mins
$online = ($last_active_time + 600 > time()) ? True : False;

<script type="text/javascript">
window.onclose = function()
{
// use jquery to make an ajax post to your chats controller, telling it someone has signed off.
// CURRENT_USER_ID will have to be passed from your application to JS, or you could try to read your session cookie there...maybe
$.post('/chats/signed_off', {user_id: CURRENT_USER_ID});
}
</script>
That's the logic. The implementation will be specific to your application, which we don't know anything about.

Related

how to check user is online or not in real TIME

I'm currently trying to display all online users on my SITE'S userpage using the php session variables. To do this, whenever a user logs in or out, a column in a database gets set to "1" or "0".. However this doesn't entirely work since the database doesn't get updated when the user closes their browser (and therefor destroys the session). So is there another way of checking if a certain sessionid is set??
I also want to know how the twitter and facebook handle this ?
You almost have it. The way that the vast majority of sites deal with the issue is to have a table like you do, but they add a timestamp to it and update the timestamp when a new page is loaded.
When querying the table, you simply look for say the last five minutes of active users and they are the "live" users on the site.
Technically, you don't even need to keep the "logged in/out" value in that table. If they have been logged in within the lat five minutes, they are probably still about.
There is no guaranteed, sure-fire, totally bullet-proof way of checking if a user is there or not. You can do some tricky JS to ping on and off, you can add even more JS that will try to alert the db when the user navigates away from the page - but at the end of the day, you cannot do anything if a browser is closed unexpectedly, or if that user loses power, or network.
On top of that web browsing is by default stateless and doesn't maintain a connection to the user after the server has finished sending code. The best we can efficiently do is update a table when the user does something new and assume they will be around for a few minutes at least.
I haven't checked but Twitter and Facebook most likely have Javascript code which notifies the server when somebody closes the page, probably coupled with a periodic heartbeat and timeout.
Check the onunload event and XMLHTTPRequest to see how you can make a request to your PHP application notifying of an user leaving (a library like jQuery might help you do this much more easily).
Add a field "last_visit" to user's Table and update it every time when user visit your site
When user login to your site find "last_visit" time and current time,after that use this function
$time_period = floor(round(abs($current_time - $last_visit)/60,2));
if ($time_period <= 10)
$online_offline_status = 1;
else
$online_offline_status = 0;
}
and then print your final result
<?php if (
$online_offline_status == 0){ ?>
<span style="color:#FF0000;">Offline</span>
<?php } else if ($online_offline_status == 1) {?>
<span style="color:#669900;">Online</span>
<?php }?>

Can't make query after session expired

I've binged a lot for this stuff, but couldn't find direct ANSWER,
I've searched for this here,
But
I am still beating my head against the wall trying to implement,
How do I do update query after session expired?
I'm not talking about explicit clicking "Logout" button
Here's basic SQL structure:
CREATE TABLE auth_users (
email varchar(40) NOT NULL,
password varchar(40) NOT NULL,
online ENUM('1') DEFAULT NULL <-- HERE, it updates to 1 when user logged in, it updates back to NULL when user explicitly clicks on LOGOUT
) type=MyISAM;
Class Hierarchy:
interface {
function login();
function logout();
//calls after succes authorization
function set_as_online();
//calls from within logout() method
function set_as_offline();
}
BUT IT DOES NOT UPDATES BACK TO NULL WHEN USER CLOSES HIS BROWSER,
For example,
Assume we have two users: User-A, User-B
User A logged successfully, now User-B can see User-A as ONLINE user.
If User-A forget to click "LOGOUT" and would close his browser,
user-B still can see User-A as ONLINE. That's the problem.
For example,
Facebook handles this very well,
Assume your friend just closed the browser (i.e his session does not exists anymore),
then somehow you can see him as OFFLINE
What am I doing wrong? Incorrect approach of handling offline/online users?
Another approach is needed here i think. Don't set a online/offline flag, but a 'last_seen' timestamp. Ie. with every request update the record to the current timestamp. If you want to know if the user is online, just do:
if($current_time - $last_seen_time < $session_expire_limit) {
// online
} else {
// offline
}
Otherwise you'd need a cronjob of some sort to automatically reset the online flag in your database after a certain time, but then still you'd need a last_seen column.
// edit
i don't know exactly how facebook does it, but it could be one of the following; for the chat and notify functionality facebook opens up a 'stream', which is in fact a little ajax call which is kept alive by the server (btw, this ajax call is refreshed every 40 seconds). Possibly this stream is used to track online users. Another option, but less likely, is that an event is attached to the window.unload event. This is less likely because a page refresh, a clicked link to another facebook page etc. is also triggering the event. This would mean that every time an internal facebook link is clicked the event should be unbinded from the browser.
Can't think of another way atm, just some suggestions. Unfortunately those are quite labor-heavy to implement, I assume my suggestion above (before the edit) should be suitable for a common website.
I am not sure how facebook controls this stuff but i can suggest you from the top of my head how i would approach this matter.
I would add a new field on your auth_users table of type Date that will represent the session_expiry_time .
Then inside your html pages you should implement some silent ajax code that will call a dummy php page on the server (the interval is something very important because you have to balance performance and functionality). This dummy page will update the session_expiry_time of the user in
the auth_users table.
Therefore, in any given time, checking a user's session_expiry_time against current time will determine if the user is online or not.
http://de2.php.net/manual/en/features.connection-handling.php
you can with register_shutdown_function() und connection_aborted() your intend achieve
Use a simple JavaScript on the page
In the body tag
The callLogoff() should be replaced with the JavaScript function that calls log off.
Try it.

Countdown variable across many pages

I have a demo website for an e-test where each student is allowed 15 minutes for the whole exam (which comprises 5 subjects, each with 10 questions). I want it that, immediately a student clicks START on the home page, a countdown timer should start and update itself automatically. Actually, that is easily done for a single page.
The problem is if the student clicks to go the next page, I want the timer to begin from where it stopped on the previous page and continue counting down.
I thought of using SESSIONS but then how do I get Javascript to set the SESSION variable in PHP? The idea was to use AJAX but I do not know how to go about it.
Can anyone help me on it, even if it requires something other than AJAX?
PS:
What I want displayed is the number of seconds left, not the current time.
Thanks.
You don't have to know where it stopped on the other page.
You just want to know when the users clicked start.
Just save that in a database or a file even.
And on every request calculate the time left on the SERVER.
Since the client can be easily manipulated.
With the time left calculated on the server you can make a countdown using javascript on every page.
I found i simple way to do it, with a small search. Here
PHP:
//when you start
$_SESSION['start_time'] = time();
Then on every page:
<script type="text/javascript">
var startTime = <?php echo $_SESSION['start_time']; ?>;
//calculate remaining time
</script>
You can use an algorithm like this:
When the "start" event occurs, store the start time in a database.
Periodically send AJAX requests to a backend script. If the time has expired, return a response that ends the test.
There is not a real "timer" in this case -- just a start time, and logic to check if 15 minutes have passed since that time. If you want to display a timer to the user, the math will be straightforward.
You could just put the pages in IFrames and the countdown timer on the main page.
Simple, you store the timestamp of when the student first started the test and output it to each page. Then it's a simple matter of substracting current time from that timestamp to get elapsed time.
However, depending on Javascript is a very bad way of ensuring that this timer gets started. A better method is to force the user to click on an actual link/button, WITHOUT involving Javascript. You record the timestamp on the server then that hit comes in, and after that everything's fine.
start.php:
Start Test - Page 1
page1.php:
<?php
if(!isset($_SESSION['test_start_timestamp')) {
$_SESSION['test_start_timestamp'] = time();
}
?>
<h3>Question #1</h3>
etc...
The important thing is to never reset the timestamp value in the session once it's been set. Otherwise the test taker can simply click around until they reach a page where the counter's reset, and they can get more time for the test.

How to handle user online status when he/she close the browser?

I am having table to track user online status by setting 'is_online' field to 1. Now User get logged in the site and shut down his/her system or power down at that time he/she logged in.
Here in database 'is_login' has the value '1' which means he is still using the site.
So I have to do some logic to change that value to '0'.
How can i handle this situation using PHP ?
The normal solution is to store a timestamp in the table which you update every time the user does something. Users with a recent timestamp (say, five minutes) are shown as logged in, everybody else are logged out.
It doesn't even have to be updated on every page load. Keep a timestamp in the session with the last update time as well, and only update the table when the database flag are about to expire.
Store an time-since-last-activity. When it's been longer then a specified time - treat as if offline. You should replace the is_online with an DateTime field, and update it every time the logged in user visits the website.
On the place you want to select all online users, instead of :
SELECT * FROM users WHERE is_online = 1
You could use:
SELECT * FROM users WHERE is_online >= DATE_SUB(NOW(), INTERVAL 5 MINUTE)
you can't. HTTP closes the connection once the page has been delivered. On the server side alone all you could do is checking if a user has requested a page within a certain amount of time.
JavaScript might be your friend. You could use it to create a ping to a php script which then updates the last request timestamp. Once there is no more pinging, the user is gone and you'd know.
If you have trouble with javaScript, a good point to start would be here: http://www.w3schools.com/JS/
You might want to focus on the AJAX and HTTP request stuff.
cu
Roman
You can use jquery to update your site each X time, so a function is executed each 10 seconds, as following code:
function updateTheBBDD(){
... calling mysql_connect -> mysql_insert -> mysql_close
}
setInterval("updateTheBBDD()",10000);
Also, when painting the user status monitor instead of consulting the BD and:
1->green
0->red
You should:
actual - time > 10 ---> red
actual - time <= 10 ---> green
Due to the stateless nature of the web it is not possible to know exactly when the user left your website. So you can't really trigger any code to change the mentioned value.
As the other have said one has to store the time-since-last-activity to get an approximate idea when was the last time the user was actually doing something with the website.
HTH :)

jquery - refresh the page when new data stored in to the table across the browser sessions

Environment : PHP/MySQL/Jquery
I would like to refresh the page (ex: index.php) when new data stores in to the table (ex : new_entry_table) checking for every one minute. The same page will be opened in many machines(pc-browsers) at a time all should get refresh when new data arises.
using jquery and database check i tried the following:
setInterval(function(){
$.post("new_data_check.php", function(data) {
if(data > 0){
$("#container").fadeOut('fast').load(location.reload());
}
});
return false;
},60000);
new_data_check.php: : checks
for new data in the test_db where
newdata_field=0 ; : If any new
data arises echo "1"; And update the
newdata_field=1; to stop constantly
refreshing the page. : else echo
"0"; : Just for a trigger
So the above jquery code checks new_data_check.php every 1 min for the trigger , if any trigger arises it will refresh the container.But its getting refresh only one opened session other opened sessions(in other browser or other pc) not getting refreshed.
Suggest a better way to do this. Thanks.
Your new_data_check.php file will need to keep track of all the users that are independently viewing the page.
If not, this will happen:
User 1 and User 2 are both logged into the site.
User 1 does the check 5 seconds before User 1, there is new data.
User 1 completes his request. The server clears the new_data bit.
User 2's request arrives 5 second later. Hedoes his request, but at this point, User 1 has set the new_data field to 0. His data is stale, but User 1 has effectively co-opted him.
By the looks of it, you're not supplying it with any information that would identify the user - unless the server is determining that using the IP address. If that's the case, remember that it's likely everyone behind a small network is going to have the same external ip address. So it can't tell people at an office apart.
What you could do is generate some kind of unique hash for each session and pass that off to the browser. The javascript can then provide the php script that same token.
Another solution without any sort of special bit, would be to pass along a timestamp with the request. Essentially, the client says "my latest bit of data arrived at 9:21:53 PM" The server then checks and responds "My most recent data was created before that, so you're still good. " or "I've got something that was created or modified on 9:22:53PM, you should download it."
With that method, you don't need to worry about who's who. Instead, you need to have modification/creation times on the data you're checking for staleness. You also need to make sure that the clients clock is synchronized correctly - better yet, don't trust the clients date and time information. Maybe utilize your new_data_check.php to provide the script with a timestamp it can pass along on subsequent requests.

Categories