Page 1 of 2

Small problem

Posted: Sat Jan 08, 2005 6:07 pm
by Log2
Ok, I have a small problem with a bit of easy code, here's what i have:

Code: Select all

if (){
$online = "Online";
}
else{
$online = "Offline";
}
I need to know what I should put in the if statement, I want it to be abled to tell if a user is online or offline, if you need variables just post and ask, but it's all the same, username, userlevel, timestamp, and email(those aren't the actual variables those are what the variables are set at) thanks

Posted: Sat Jan 08, 2005 6:12 pm
by markl999
search this forum for "users online" and/or "who's online" as it's been asked before and could get a little more complicated that what you have above, eg what if they don't hit 'logout' and leave your site .. you need a way to 'clear' idle users too.

Posted: Sat Jan 08, 2005 6:19 pm
by Log2
maybe im not being clear, I have a table that states the user, the email and i want it say either online or offline, I don't care if they hit logout because i have a couter to show how many users are online and how many guests are online. the list of variables are:

Code: Select all

$uname  = mysql_result($result,$i,"username");
	      $ulevel = mysql_result($result,$i,"userlevel");
	      $email  = mysql_result($result,$i,"email");
	      $time   = mysql_result($result,$i,"timestamp");
and some extra info would be that there is an if ($session->logged_in){ statement at the top (i've tried that, doesn't work) but i will let you work with that

Posted: Sat Jan 08, 2005 6:22 pm
by markl999
If you are storing 'logged_in' in a session when they are logged in then you could use:

Code: Select all

if(isset($_SESSION['logged_in'])){
} else {
}
If not you need to tell us what defines a logged in / online person?

Posted: Sat Jan 08, 2005 6:26 pm
by Log2
feyd | Help us, help you. Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]


ok i have
$this->calcNumActiveUsers(); to calculate the active users;
This might help you(doubt it)

Code: Select all

function confirmUserID($username, $userid){
      /* Add slashes if necessary (for query) */
      if(!get_magic_quotes_gpc()) {
	      $username = addslashes($username);
      }

      /* Verify that user is in database */
      $q = "SELECT userid FROM ".TBL_USERS." WHERE username = '$username'";
      $result = mysql_query($q, $this->connection);
      if(!$result || (mysql_numrows($result) < 1)){
         return 1; //Indicates username failure
      }

      /* Retrieve userid from result, strip slashes */
      $dbarray = mysql_fetch_array($result);
      $dbarray['userid'] = stripslashes($dbarray['userid']);
      $userid = stripslashes($userid);

      /* Validate that userid is correct */
      if($userid == $dbarray['userid']){
         return 0; //Success! Username and userid confirmed
      }
      else{
         return 2; //Indicates userid invalid
      }
   }
and this would be the last thing that might help

Code: Select all

function calcNumActiveUsers(){
      /* Calculate number of users at site */
      $q = "SELECT * FROM ".TBL_ACTIVE_USERS;
      $result = mysql_query($q, $this->connection);
      $this->num_active_users = mysql_numrows($result);
   }
uhh it didn't work, it either says everyone is offline or everyone is online depending on what i try


feyd | Help us, help you. Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Sat Jan 08, 2005 6:37 pm
by markl999
Maybe it's me that's confused :o .. but when one of your users logs in correctly then how do you know from that point on that they are logged in so they don't constantly have to do so? Do you update a field in the database (eg a logged_in field from 0 to 1) or create a session variable for them (eg $_SESSION['logged_in']) ?
Knowing how many people are online is usually a matter of counting active sessions or counting logged in users if you don't want to count visitors/guests who ar'nt logged in.

Posted: Sat Jan 08, 2005 6:41 pm
by Log2
i put this code at the top of every page include("include/session.php"); :)

Posted: Sat Jan 08, 2005 6:46 pm
by markl999
Right .. i'm presuming that starts a session, so every one who visits your site gets a session cookie?
How are you storing sessions ... just using the default method of files or storing them in a database?

Posted: Sat Jan 08, 2005 6:58 pm
by Log2
here, this is session.php

Code: Select all

<?

include("database.php");
include("mailer.php");
include("form.php");

class Session
&#123;
   var $username;     //Username given on sign-up
   var $userid;       //Random value generated on current login
   var $userlevel;    //The level to which the user pertains
   var $time;         //Time user was last active (page loaded)
   var $logged_in;    //True if user is logged in, false otherwise
   var $userinfo = array();  //The array holding all user info
   var $url;          //The page url current being viewed
   var $referrer;     //Last recorded site page viewed
   /**
    * Note: referrer should really only be considered the actual
    * page referrer in process.php, any other time it may be
    * inaccurate.
    */

   /* Class constructor */
   function Session()&#123;
      $this->time = time();
      $this->startSession();
   &#125;

   /**
    * startSession - Performs all the actions necessary to 
    * initialize this session object. Tries to determine if the
    * the user has logged in already, and sets the variables 
    * accordingly. Also takes advantage of this page load to
    * update the active visitors tables.
    */
   function startSession()&#123;
      global $database;  //The database connection
      session_start();   //Tell PHP to start the session

      /* Determine if user is logged in */
      $this->logged_in = $this->checkLogin();

      /**
       * Set guest value to users not logged in, and update
       * active guests table accordingly.
       */
      if(!$this->logged_in)&#123;
         $this->username = $_SESSION&#1111;'username'] = GUEST_NAME;
         $this->userlevel = GUEST_LEVEL;
         $database->addActiveGuest($_SERVER&#1111;'REMOTE_ADDR'], $this->time);
      &#125;
      /* Update users last active timestamp */
      else&#123;
         $database->addActiveUser($this->username, $this->time);
      &#125;
      
      /* Remove inactive visitors from database */
      $database->removeInactiveUsers();
      $database->removeInactiveGuests();
      
      /* Set referrer page */
      if(isset($_SESSION&#1111;'url']))&#123;
         $this->referrer = $_SESSION&#1111;'url'];
      &#125;else&#123;
         $this->referrer = "/";
      &#125;

      /* Set current url */
      $this->url = $_SESSION&#1111;'url'] = $_SERVER&#1111;'PHP_SELF'];
   &#125;

   /**
    * checkLogin - Checks if the user has already previously
    * logged in, and a session with the user has already been
    * established. Also checks to see if user has been remembered.
    * If so, the database is queried to make sure of the user's 
    * authenticity. Returns true if the user has logged in.
    */
   function checkLogin()&#123;
      global $database;  //The database connection
      /* Check if user has been remembered */
      if(isset($_COOKIE&#1111;'cookname']) && isset($_COOKIE&#1111;'cookid']))&#123;
         $this->username = $_SESSION&#1111;'username'] = $_COOKIE&#1111;'cookname'];
         $this->userid   = $_SESSION&#1111;'userid']   = $_COOKIE&#1111;'cookid'];
      &#125;

      /* Username and userid have been set and not guest */
      if(isset($_SESSION&#1111;'username']) && isset($_SESSION&#1111;'userid']) &&
         $_SESSION&#1111;'username'] != GUEST_NAME)&#123;
         /* Confirm that username and userid are valid */
         if($database->confirmUserID($_SESSION&#1111;'username'], $_SESSION&#1111;'userid']) != 0)&#123;
            /* Variables are incorrect, user not logged in */
            unset($_SESSION&#1111;'username']);
            unset($_SESSION&#1111;'userid']);
            return false;
         &#125;

         /* User is logged in, set class variables */
         $this->userinfo  = $database->getUserInfo($_SESSION&#1111;'username']);
         $this->username  = $this->userinfo&#1111;'username'];
         $this->userid    = $this->userinfo&#1111;'userid'];
         $this->userlevel = $this->userinfo&#1111;'userlevel'];
         return true;
      &#125;
      /* User not logged in */
      else&#123;
         return false;
      &#125;
   &#125;

   /**
    * login - The user has submitted his username and password
    * through the login form, this function checks the authenticity
    * of that information in the database and creates the session.
    * Effectively logging in the user if all goes well.
    */
   function login($subuser, $subpass, $subremember)&#123;
      global $database, $form;  //The database and form object

      /* Username error checking */
      $field = "user";  //Use field name for username
      if(!$subuser || strlen($subuser = trim($subuser)) == 0)&#123;
         $form->setError($field, "* Username not entered");
      &#125;
      else&#123;
         /* Check if username is not alphanumeric */
         if(!eregi("^(&#1111;0-9a-z])*$", $subuser))&#123;
            $form->setError($field, "* Username not alphanumeric");
         &#125;
      &#125;

      /* Password error checking */
      $field = "pass";  //Use field name for password
      if(!$subpass)&#123;
         $form->setError($field, "* Password not entered");
      &#125;
      
      /* Return if form errors exist */
      if($form->num_errors > 0)&#123;
         return false;
      &#125;

      /* Checks that username is in database and password is correct */
      $subuser = stripslashes($subuser);
      $result = $database->confirmUserPass($subuser, md5($subpass));

      /* Check error codes */
      if($result == 1)&#123;
         $field = "user";
         $form->setError($field, "* Username not found");
      &#125;
      else if($result == 2)&#123;
         $field = "pass";
         $form->setError($field, "* Invalid password");
      &#125;
      
      /* Return if form errors exist */
      if($form->num_errors > 0)&#123;
         return false;
      &#125;

      /* Username and password correct, register session variables */
      $this->userinfo  = $database->getUserInfo($subuser);
      $this->username  = $_SESSION&#1111;'username'] = $this->userinfo&#1111;'username'];
      $this->userid    = $_SESSION&#1111;'userid']   = $this->generateRandID();
      $this->userlevel = $this->userinfo&#1111;'userlevel'];
      
      /* Insert userid into database and update active users table */
      $database->updateUserField($this->username, "userid", $this->userid);
      $database->addActiveUser($this->username, $this->time);
      $database->removeActiveGuest($_SERVER&#1111;'REMOTE_ADDR']);

      /**
       * This is the cool part: the user has requested that we remember that
       * he's logged in, so we set two cookies. One to hold his username,
       * and one to hold his random value userid. It expires by the time
       * specified in constants.php. Now, next time he comes to our site, we will
       * log him in automatically, but only if he didn't log out before he left.
       */
      if($subremember)&#123;
         setcookie("cookname", $this->username, time()+COOKIE_EXPIRE, COOKIE_PATH);
         setcookie("cookid",   $this->userid,   time()+COOKIE_EXPIRE, COOKIE_PATH);
      &#125;

      /* Login completed successfully */
      return true;
   &#125;

   /**
    * logout - Gets called when the user wants to be logged out of the
    * website. It deletes any cookies that were stored on the users
    * computer as a result of him wanting to be remembered, and also
    * unsets session variables and demotes his user level to guest.
    */
   function logout()&#123;
      global $database;  //The database connection
      /**
       * Delete cookies - the time must be in the past,
       * so just negate what you added when creating the
       * cookie.
       */
      if(isset($_COOKIE&#1111;'cookname']) && isset($_COOKIE&#1111;'cookid']))&#123;
         setcookie("cookname", "", time()-COOKIE_EXPIRE, COOKIE_PATH);
         setcookie("cookid",   "", time()-COOKIE_EXPIRE, COOKIE_PATH);
      &#125;

      /* Unset PHP session variables */
      unset($_SESSION&#1111;'username']);
      unset($_SESSION&#1111;'userid']);

      /* Reflect fact that user has logged out */
      $this->logged_in = false;
      
      /**
       * Remove from active users table and add to
       * active guests tables.
       */
      $database->removeActiveUser($this->username);
      $database->addActiveGuest($_SERVER&#1111;'REMOTE_ADDR'], $this->time);
      
      /* Set user level to guest */
      $this->username  = GUEST_NAME;
      $this->userlevel = GUEST_LEVEL;
   &#125;

   /**
    * register - Gets called when the user has just submitted the
    * registration form. Determines if there were any errors with
    * the entry fields, if so, it records the errors and returns
    * 1. If no errors were found, it registers the new user and
    * returns 0. Returns 2 if registration failed.
    */
   function register($subuser, $subpass, $subemail)&#123;
      global $database, $form, $mailer;  //The database, form and mailer object
      
      /* Username error checking */
      $field = "user";  //Use field name for username
      if(!$subuser || strlen($subuser = trim($subuser)) == 0)&#123;
         $form->setError($field, "* Username not entered");
      &#125;
      else&#123;
         /* Spruce up username, check length */
         $subuser = stripslashes($subuser);
         if(strlen($subuser) < 5)&#123;
            $form->setError($field, "* Username below 5 characters");
         &#125;
         else if(strlen($subuser) > 15)&#123;
            $form->setError($field, "* Username above 30 characters");
         &#125;
         /* Check if username is not alphanumeric */
         else if(!eregi("^(&#1111;0-9a-z])+$", $subuser))&#123;
            $form->setError($field, "* Username not alphanumeric");
         &#125;
         /* Check if username is reserved */
         else if(strcasecmp($subuser, GUEST_NAME) == 0)&#123;
            $form->setError($field, "* Username reserved word");
         &#125;
         /* Check if username is already in use */
         else if($database->usernameTaken($subuser))&#123;
            $form->setError($field, "* Username already in use");
         &#125;
         /* Check if username is banned */
         else if($database->usernameBanned($subuser))&#123;
            $form->setError($field, "* Username banned");
         &#125;
      &#125;

      /* Password error checking */
      $field = "pass";  //Use field name for password
      if(!$subpass)&#123;
         $form->setError($field, "* Password not entered");
      &#125;
      else&#123;
         /* Spruce up password and check length*/
         $subpass = stripslashes($subpass);
         if(strlen($subpass) < 4)&#123;
            $form->setError($field, "* Password too short");
         &#125;
         /* Check if password is not alphanumeric */
         else if(!eregi("^(&#1111;0-9a-z])+$", ($subpass = trim($subpass))))&#123;
            $form->setError($field, "* Password not alphanumeric");
         &#125;
         /**
          * Note: I trimmed the password only after I checked the length
          * because if you fill the password field up with spaces
          * it looks like a lot more characters than 4, so it looks
          * kind of stupid to report "password too short".
          */
      &#125;
      
      /* Email error checking */
      $field = "email";  //Use field name for email
      if(!$subemail || strlen($subemail = trim($subemail)) == 0)&#123;
         $form->setError($field, "* Email not entered");
      &#125;
      else&#123;
         /* Check if valid email address */
         $regex = "^&#1111;_+a-z0-9-]+(\.&#1111;_+a-z0-9-]+)*"
                 ."@&#1111;a-z0-9-]+(\.&#1111;a-z0-9-]&#123;1,&#125;)*"
                 ."\.(&#1111;a-z]&#123;2,&#125;)&#123;1&#125;$";
         if(!eregi($regex,$subemail))&#123;
            $form->setError($field, "* Email invalid");
         &#125;
         $subemail = stripslashes($subemail);
      &#125;

      /* Errors exist, have user correct them */
      if($form->num_errors > 0)&#123;
         return 1;  //Errors with form
      &#125;
      /* No errors, add the new account to the */
      else&#123;
         if($database->addNewUser($subuser, md5($subpass), $subemail))&#123;
            if(EMAIL_WELCOME)&#123;
               $mailer->sendWelcome($subuser,$subemail,$subpass);
            &#125;
            return 0;  //New user added succesfully
         &#125;else&#123;
            return 2;  //Registration attempt failed
         &#125;
      &#125;
   &#125;
   
   /**
    * editAccount - Attempts to edit the user's account information
    * including the password, which it first makes sure is correct
    * if entered, if so and the new password is in the right
    * format, the change is made. All other fields are changed
    * automatically.
    */
   function editAccount($subcurpass, $subnewpass, $subemail)&#123;
      global $database, $form;  //The database and form object
      /* New password entered */
      if($subnewpass)&#123;
         /* Current Password error checking */
         $field = "curpass";  //Use field name for current password
         if(!$subcurpass)&#123;
            $form->setError($field, "* Current Password not entered");
         &#125;
         else&#123;
            /* Check if password too short or is not alphanumeric */
            $subcurpass = stripslashes($subcurpass);
            if(strlen($subcurpass) < 4 ||
               !eregi("^(&#1111;0-9a-z])+$", ($subcurpass = trim($subcurpass))))&#123;
               $form->setError($field, "* Current Password incorrect");
            &#125;
            /* Password entered is incorrect */
            if($database->confirmUserPass($this->username,md5($subcurpass)) != 0)&#123;
               $form->setError($field, "* Current Password incorrect");
            &#125;
         &#125;
         
         /* New Password error checking */
         $field = "newpass";  //Use field name for new password
         /* Spruce up password and check length*/
         $subpass = stripslashes($subnewpass);
         if(strlen($subnewpass) < 4)&#123;
            $form->setError($field, "* New Password too short");
         &#125;
         /* Check if password is not alphanumeric */
         else if(!eregi("^(&#1111;0-9a-z])+$", ($subnewpass = trim($subnewpass))))&#123;
            $form->setError($field, "* New Password not alphanumeric");
         &#125;
      &#125;
      /* Change password attempted */
      else if($subcurpass)&#123;
         /* New Password error reporting */
         $field = "newpass";  //Use field name for new password
         $form->setError($field, "* New Password not entered");
      &#125;
      
      /* Email error checking */
      $field = "email";  //Use field name for email
      if($subemail && strlen($subemail = trim($subemail)) > 0)&#123;
         /* Check if valid email address */
         $regex = "^&#1111;_+a-z0-9-]+(\.&#1111;_+a-z0-9-]+)*"
                 ."@&#1111;a-z0-9-]+(\.&#1111;a-z0-9-]&#123;1,&#125;)*"
                 ."\.(&#1111;a-z]&#123;2,&#125;)&#123;1&#125;$";
         if(!eregi($regex,$subemail))&#123;
            $form->setError($field, "* Email invalid");
         &#125;
         $subemail = stripslashes($subemail);
      &#125;
      
      /* Errors exist, have user correct them */
      if($form->num_errors > 0)&#123;
         return false;  //Errors with form
      &#125;
      
      /* Update password since there were no errors */
      if($subcurpass && $subnewpass)&#123;
         $database->updateUserField($this->username,"password",md5($subnewpass));
      &#125;
      
      /* Change Email */
      if($subemail)&#123;
         $database->updateUserField($this->username,"email",$subemail);
      &#125;
      
      /* Success! */
      return true;
   &#125;
   
   /**
    * isAdmin - Returns true if currently logged in user is
    * an administrator, false otherwise.
    */
   function isAdmin()&#123;
      return ($this->userlevel == ADMIN_LEVEL ||
              $this->username  == ADMIN_NAME);
   &#125;
   function isAdmin2()&#123;
   	  return ($this->userlevel == ADMIM2_LEVEL ||
	  		  $this->username  == ADMIM2_NAME);
   &#125;
   /**
    * generateRandID - Generates a string made up of randomized
    * letters (lower and upper case) and digits and returns
    * the md5 hash of it to be used as a userid.
    */
   function generateRandID()&#123;
      return md5($this->generateRandStr(16));
   &#125;
   
   /**
    * generateRandStr - Generates a string made up of randomized
    * letters (lower and upper case) and digits, the length
    * is a specified parameter.
    */
   function generateRandStr($length)&#123;
      $randstr = "";
      for($i=0; $i<$length; $i++)&#123;
         $randnum = mt_rand(0,61);
         if($randnum < 10)&#123;
            $randstr .= chr($randnum+48);
         &#125;else if($randnum < 36)&#123;
            $randstr .= chr($randnum+55);
         &#125;else&#123;
            $randstr .= chr($randnum+61);
         &#125;
      &#125;
      return $randstr;
   &#125;
&#125;;


/**
 * Initialize session object - This must be initialized before
 * the form object because the form uses session variables,
 * which cannot be accessed unless the session has started.
 */
$session = new Session;

/* Initialize form object */
$form = new Form;

?>
just so you know whats in session.php

Posted: Sat Jan 08, 2005 7:11 pm
by markl999
Okie, that helps. Looks like you were on the right track with:

Code: Select all

function calcNumActiveUsers(){
   /* Calculate number of users at site */
   $q = "SELECT * FROM ".TBL_ACTIVE_USERS;
   $result = mysql_query($q, $this->connection);
   $this->num_active_users = mysql_numrows($result);
}
But if you just want to know if a user is online or offline then don't you need a function along the lines of:

Code: Select all

function isUserOnline($username){
   /* Check if a user is online */
   $q = "SELECT * FROM ".TBL_ACTIVE_USERS." WHERE username='$username'";
   $result = mysql_query($q, $this->connection);
   return mysql_num_rows($result);
}
//and use it something like
if(isUserOnline($someusername)){
} else {
}
You'll need to amend to suite of course, i.e you might need if($this->isUserOnline ... if the function is a method of a class, and i've used the username as it looks like the active users table uses that and not the userid. (and you might not want SELECT *, but use SELECT COUNT(*) or whatever .. ;))

Posted: Sat Jan 08, 2005 7:14 pm
by Log2
so could i put if(isuseronline($uname)){ with the vars that i gave you?

Posted: Sat Jan 08, 2005 7:19 pm
by markl999
Well as you're using $this->connection inside the function it looks like this belongs inside a class, so you'd need if($this->isUserOnline($uname)){ .. } else { .. }
It depends where exactly you intend to call the isUserOnline function/method from, inside a class or outside?

Posted: Sat Jan 08, 2005 7:21 pm
by Log2
Fatal error: Call to a member function on a non-object

Posted: Sat Jan 08, 2005 7:25 pm
by markl999
It depends where exactly you intend to call the isUserOnline function/method from, inside a class or outside?
If you've placed this function outside of a class then just use if(isUserOnline($uname)) .. but you'll need to amend the function so it has access to the database as all your previous examples/function are class methods and use $this->database .. it would seem to make sense to put this function inside session.php as that (strangely) seems to be handling all the user related operations.

Posted: Sat Jan 08, 2005 7:29 pm
by Log2
I have a variable in database.php called $num_active_users