My website is http://www.stickmin.com/ (Please Register!)

I have it so when a user Logs In it updates their status to "Online" and if a user clicks Logout it updates their status to "Offline"...

The problem I have is that some users just click the exit button on their browser and their status doesn't get updated. I need a script to make users logout when they exit... thanks!

Hmm. Try storing the session in a database.
Create a new column in your users table, call it logged or something.

Create another php file, that you'll include at the top of all your pages or so.

<?php include "sessionStore.php"; ?>

Then add something similar to the following to the file, change according to your own field names.

<?php
session_start();

if(isset($_SESSION['userID'])) {
$setLogged= mysql_query("UPDATE `useraccounts` SET `logged` = '".time()."' WHERE `id` = '".$_SESSION['userID']."'") or die(mysql_error());
}
?>

If you'd like to display online under a user name like in a forum post. Add something similar to the following:

<?php
$loggedtime = time() - 300; // 5 minutes

/*Now since in the forum section, the php code is looping and displaying user name, post, reply link etc.. at the same time you will want to utilize the query and check the logged column, I will suppose that: $row = mysql_fetch_array['$fetchPosts'] , where $fetchPosts is the variable name of your mysql query. */

if($row['logged'] > $loggedtime) { ?>
<img src="online.jpg" />  <?php } //Guess you might want to use an image to show online status
else { ?>
<img src="offline.jpg" /> 
<? } ?>

If you want to display all logged users somewhere else on your site, you'd use a query like this instead:

<?php
$getLogged = mysql_query("SELECT `userID` FROM `useraccounts` WHERE `logged` > '".$loggedtime."' ORDER BY `userID` ASC") or die(mysql_error());
if(mysql_num_rows($getLogged) > 0){
while($logged= mysql_fetch_array($getLogged){
echo $logged['userID']; ?> <br />
<?php 
}
} //end if
else echo "No user is online. :(";
?>

Hope that helps something. Most probably a better way out there.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.