Jump to content

user is online help


Glenskie

Recommended Posts

ok i want to make it to where when you look at there profile it will tell you if they are online or not!

how would i do that ? here is my php script that has some modifications on the profile page but wont show if other users are online! here is the login script where i put the session and the profile page.

login.php


<?php



// Start Session to enable creating the session variables below when they log in

session_start();

// Force script errors and warnings to show on page in case php.ini file is set to not display them

error_reporting(E_ALL);

ini_set('display_errors', '1');

//-----------------------------------------------------------------------------------------------------------------------------------

// Initialize some vars

$errorMsg = '';

$email = '';

$pass = '';

$remember = '';

if (isset($_POST['email'])) {

    

    $email = $_POST['email'];

    $pass = $_POST['pass'];

    if (isset($_POST['remember'])) {

        $remember = $_POST['remember'];

    }

    $email = stripslashes($email);

    $pass = stripslashes($pass);

    $email = strip_tags($email);

    $pass = strip_tags($pass);

    

    // error handling conditional checks go here

    if ((!$email) || (!$pass)) { 



        $errorMsg = '<font color="red">Please fill in both fields</font>';



    } else { // Error handling is complete so process the info if no errors

        include 'scripts/connect_to_mysql.php'; // Connect to the database

        $email = mysql_real_escape_string($email); // After we connect, we secure the string before adding to query

        //$pass = mysql_real_escape_string($pass); // After we connect, we secure the string before adding to query

        $pass = md5($pass); // Add MD5 Hash to the password variable they supplied after filtering it

        // Make the SQL query

        $sql = mysql_query("SELECT * FROM myMembers WHERE email='$email' AND password='$pass' AND email_activated='1'"); 

        $login_check = mysql_num_rows($sql);

        // If login check number is greater than 0 (meaning they do exist and are activated)

        if($login_check > 0){ 

                while($row = mysql_fetch_array($sql)){

                    

                    // Pleae note: Adam removed all of the session_register() functions cuz they were deprecated and

                    // he made the scripts to where they operate universally the same on all modern PHP versions(PHP 4.0  thru 5.3+)

                    // Create session var for their raw id

                    $id = $row["id"];   

                    $_SESSION['id'] = $id;

                    // Create the idx session var

                    $_SESSION['idx'] = base64_encode("g4p3h9xfn8sq03hs2234$id");

                    // Create session var for their username

                    $username = $row["username"];

                    $_SESSION['username'] = $username;

                    //THIS IS WHERE I EDITED THE SESSION TO SAY IF THERE LOGGED IN OR NOT

                    $logedin = $row['id'];

                    $_SESSION['islogedin']=$logedin;

                    mysql_query("UPDATE myMembers SET last_log_date=now() WHERE id='$id' LIMIT 1");

                    // THIS WAS JUST A TEST BUT WONT UPDATE UNTILL THEY LOGOUT

                    mysql_query("UPDATE myMembers SET online='online' WHERE id='$id' LIMIT 1");

                    

                    

                } // close while

    

                // Remember Me Section

                if($remember == "yes"){

                    $encryptedID = base64_encode("g4enm2c0c4y3dn3727553$id");

                    setcookie("idCookie", $encryptedID, time()+60*60*24*100, "/"); // Cookie set to expire in about 30 days

                    setcookie("passCookie", $pass, time()+60*60*24*100, "/"); // Cookie set to expire in about 30 days

                } 

                // All good they are logged in, send them to homepage then exit script

                header("location: home.php?test=$id"); 

                exit();

    

        } else { // Run this code if login_check is equal to 0 meaning they do not exist

            $errorMsg = "<h3><font color='red'>Email/Password invalid<br /></font></h3><a href='forgot_pass.php'>Forgot password?</a><div align='right'> <br> Forget to activate you account?</div>";

        } 

        



    } // Close else after error checks



} //Close if (isset ($_POST['uname'])){



?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<link rel="icon" href="favicon.ico" type="image/x-icon" />

<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />

<link href="style/main.css" rel="stylesheet" type="text/css" />

<script src="js/jquery-1.4.2.js" type="text/javascript"></script>

<title>Log In</title>

<title>Login Page</title>

   <style type="text/css">

        #stage {

            top: 0px;

            left: 0px;

            z-index: 100;

        }

        .stage {

            position: absolute;

            top: 0;

            left: 0;

            width: 100%;

            min-width: 900px;

            height: 1359px;

            overflow: hidden;

        }

        #bg {

            background: #aedfe5 url(images/sky1.png) 0 0 repeat-x;

        }

        #clouds {

            background: transparent url(images/cloud.png) 305px 10px repeat-x;

        }

        #sun

        {

            background:  url(images/land_sun.gif)0 0 no-repeat;

        }

        #hillbottom

        {

            background: url(images/hill2.png)0 1270px repeat-x;

        }

    </style>

    <link rel="stylesheet" type="text/css" href="css/loginstyle.css" /></head>

<body>

<!-- IE6 fixes are found in styles/ie6.css -->

    <!--[if lte IE 6]><link rel="stylesheet" type="text/css" href="css/ie6.css" /><![endif]-->

    

    <script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>

    <script src="js/jquery-ui-1.7.2.spritely.custom.min.js" type="text/javascript"></script>

    <script src="js/jquery.spritely-0.5.js" type="text/javascript"></script>



    <script type="text/javascript">

    (function($) {

            $(document).ready(function() {

                

                

                    

                var direction = 'left';

                

                



                $('#clouds').pan({fps: 40, speed: 0.5, dir: direction, depth: 10});

                

                

            });

        })(jQuery);

    

    </script><div id="bg" class="stage"></div> 

    <div id="container">

    <div id="sun" class="stage"></div>

    <div id="clouds" class="stage">

        <div id="stage" class="stage">

<body>

<div id="behindform">

  <form id="signinform" action="login.php" method="post" enctype="multipart/form-data" name="signinform">

    <fieldset>

    

      <legend>Log in</legend>

     

      <label for="login">Email</label>

      <input type="text" id="email" name="email" />

      <div class="clear"></div>

      

      <label for="password">Password</label>

      <input type="password" id="password" name="pass" />

      <div class="clear"></div>

      

      <label for="remember_me" style="padding: 0;">Remember me?</label>

      <input type="checkbox" id="remember" style="position: relative; top: 3px; margin: 0; " name="remember"/ value="yes" checked="checked">

      <div class="clear"></div>

      

      <br />

      

      <input type="submit" style="margin: -20px 0 0 287px;" class="button" name="commit" value="Sign In"/> 

    </fieldset><?php print "$errorMsg"; ?>

  </form>

  </div>

  </div>

  </div><div id="hillbottom" class="stage"> </div>

  

  





    

    

</body>

</html>

profile.php This is only a part where i try. but when i putt it on , it wont echo the other peoples on , like it doesnt get the other sessions or somethig


//HERE IS WHERE I STARTED , BUT dONT KNOW WHAT TO DO !

if (isset($_SESSION['islogedin']) && $logOptions_id != $id) {

    $isonline = "<font color='green'>online</font>";

}

else{

    $isonline = "<font color='red'>offline</font>";

    }



// This is to Check if user is online or not! needs editing

//$isonline = mysql_query("SELECT online FROM myMembers WHERE id='$logOptions_id'AND online='online'");

//$isonlinecheck=mysql_query($isonline);

//if ($isonlinecheck ="online"){

//$online = "is <font color='green'>online!</font>";}

//else {

//    $online = "is<font color='red'> offline!</font>";

//}

// End to Check if user is online or not!

?>

Link to comment
Share on other sites

This same question has been asked/answered many times in this forum. Do a search next time. But, to - briefly - answer your question:

 

You can't really know who is online. Most users never "log out" of a web application - they just close their browser. So, you have to determine who is online based upon their last activity. You need to come up with a time period in which you consider a user as "online" if they have recorded any activity. You would need to store a timestamp every time a user accesses a page as that user's "last_access" time. Then, to find all users who are "online" you need to query all users who have a "last_activity" within the set time period. So, if your time period is 5 minutes, then you would count anyone with a recorded activity (page access) within the last 5 minutes as "online".

Link to comment
Share on other sites

This same question has been asked/answered many times in this forum. Do a search next time. But, to - briefly - answer your question:

 

You can't really know who is online. Most users never "log out" of a web application - they just close their browser. So, you have to determine who is online based upon their last activity. You need to come up with a time period in which you consider a user as "online" if they have recorded any activity. You would need to store a timestamp every time a user accesses a page as that user's "last_access" time. Then, to find all users who are "online" you need to query all users who have a "last_activity" within the set time period. So, if your time period is 5 minutes, then you would count anyone with a recorded activity (page access) within the last 5 minutes as "online".

if you use sessions to determine if someone is online/offline, and you have the session lifetime directive set to 0 in their php.ini file.. if they close their browser, their session will be terminated.. thus they will appear offline..

Link to comment
Share on other sites

if you use sessions to determine if someone is online/offline, and you have the session lifetime directive set to 0 in their php.ini file.. if they close their browser, their session will be terminated.. thus they will appear offline..

 

So how do you detect that their cookie has expired server-side if they've closed their browser and are no longer making requests?

Link to comment
Share on other sites

This same question has been asked/answered many times in this forum. Do a search next time. But, to - briefly - answer your question:

 

You can't really know who is online. Most users never "log out" of a web application - they just close their browser. So, you have to determine who is online based upon their last activity. You need to come up with a time period in which you consider a user as "online" if they have recorded any activity. You would need to store a timestamp every time a user accesses a page as that user's "last_access" time. Then, to find all users who are "online" you need to query all users who have a "last_activity" within the set time period. So, if your time period is 5 minutes, then you would count anyone with a recorded activity (page access) within the last 5 minutes as "online".

if you use sessions to determine if someone is online/offline, and you have the session lifetime directive set to 0 in their php.ini file.. if they close their browser, their session will be terminated.. thus they will appear offline..

 

If what you say is true, I would like to see some documentation on that. If a user closes their browser the server has no knowledge of that. It is the client that "drops" the session. Besides, with multi-tab browsers (from what I have found) your session isn't terminated when you close the tab that a web-site is loaded it. You have to close the entire browser. Lastly, you could store the session id in the user table, but then you have to match up all the open sessions with the users. Since session data is stored in individual files on the server that would be an expensive process.

Link to comment
Share on other sites

On top of that, you'd need a garbage collector working on overdrive to be sure every expired session entry was being wiped as soon as it was considered expired.

 

Regardless of where you store the actual data, at some point you're going to have to store a timestamp of the user's last request, determine a set time that the user will be considered inactive, and check if that stamp is older than that time.

Link to comment
Share on other sites

With knowledge of the language, your existing code, and an understanding of the theories provided in this thread.

 

Since I assume you understand what we've explained, I'm going to guess it's one of the first two that's preventing you from doing this yourself. That is an issue, because this is supposed to be a forum for people who need help with their own programs that they both understand and have developed.

 

I'd love to give you a working example stripped down to the basic issue you wanted solved, but I have a feeling it won't help as you more want a solution you can just plug into the code you've provided. If I'm wrong, I'm sorry and I'll gladly post the example.

 

If I were to give you a copy+paste solution, you wouldn't learn anything, nor would you know how to fix any issues you may encounter while using it, bringing you back here to post someone else's code you need fixed... again.

Link to comment
Share on other sites

Curiosity and a little slowness at work has caused me to give you the benefit of the doubt. Using the following MySQL table/data

 

--
-- Table structure for table `users`
--

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `last_activity` datetime NOT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=5 ;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `last_activity`) VALUES
(1, 'xyph', '2011-09-19 16:50:17'),
(2, 'glenski', '2011-09-19 16:48:59'),
(3, 'user1', '2011-09-19 16:49:45'),
(4, 'user2', '2011-09-19 16:50:31');

 

I have designed this single-file log-in script that tracks other user's activities

<?php 

// Start basic PHP session
session_start();
// Open db connection
$db = new MySQLi( 'localhost', 'root', '', 'db' );
if( $db == FALSE ) trigger_error('Unable to connect to database',E_ERROR);

// Set how many seconds until user is considered offline
$age = 60*2; // 2 minutes (60 seconds * 2)

// If session exists, update the users's last activity to now
if( !empty($_SESSION['name']) ) {
$q = 'UPDATE `users` SET `last_activity` = NOW()
	WHERE `name` = "'.$db->escape_string($_SESSION['name']).'"';
if( !$db->query($q) ) trigger_error('Bad query updating activity',E_ERROR);
}

// Check if user wants to log out, after we update the last activity
if( isset($_GET['logout']) ) {
$_SESSION = array();
session_destroy();
}

// Check if user is logged in, after we check if they wanted to log out
if( !empty($_SESSION['name']) ) {
echo '<p>Welcome, '.htmlspecialchars($_SESSION['name']).'<p>';
// Grab users that aren't you from database to get status
$q = 'SELECT `name`, DATE_FORMAT(`last_activity`,"%a, %b %e %T") as `last_activity`,
		UNIX_TIMESTAMP(`last_activity`) as `last_activity_stamp`
	FROM `users`
	WHERE `name` <> "'.$db->escape_string($_SESSION['name']).'"';
// Verify good query
if( ($r = $db->query($q)) === FALSE ) trigger_error('Bad query selecting users',E_ERROR);
// Start the list of users
echo '<ul>';
// Loop through results
while( $row = $r->fetch_assoc() )
	echo '<li>'.$row['name'].' is considered <span style="color: '.
		( ($row['last_activity_stamp'] + $age) < time() ? 'red">Offline' : 'green">Online' ).
		'</span>. Last activity was '.$row['last_activity'].'</li>';
echo '</ul>';
echo '<p><a href="?logout=1">Log out</a></p>';

// The session hasn't been started
} else {

// Check if the login form was submitted
if( !empty($_POST['name']) ) {
	$q = 'SELECT `name` FROM `users` WHERE `name` = "'.$db->escape_string($_POST['name']).'"';
	if( ($r = $db->query($q)) === FALSE ) trigger_error('Bad query logging user in',E_ERROR);
	// Check if the user exists
	if( $r->num_rows == 1 ) {
		// Init the session
		$_SESSION['name'] = $_POST['name'];
		// Redirect the user to the current page
		header( 'Location: http://'.$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'] );
		exit();
	} else {
		echo '<p>User '.htmlspecialchars($_POST['name']).' not found</p>';
	}
}
// Echo the form
echo '<div><form action="'.$_SERVER['SCRIPT_NAME'].'" method="post">'.
	'<label>Username: <input type="text" name="name"></label><br>'.
	'<input type="submit"></form></div>';

}

?>

 

Hope this helps. It's everything you need.

Link to comment
Share on other sites

I am slightly offended by that request.

 

I've already done quite a bit to help you solve your problem. Now you want me to try to sift through your unorganized code to do something simple that you can't?

 

I'm done with this thread :P Good luck convincing someone else to fix your script for you.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.