SitePoint Sponsor

User Tag List

Results 1 to 10 of 10
  1. #1
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    user online not working

    I was trying to use this script to find number of users(people) who are currently online
    But this is not working as when i get in to page and press refresh every time i press refresh counter increase by one..ie start new session
    according to this file if refresh is pressed rather it should have updated things
    what is error
    and where is error
    are there any other good file to find user online in any where...

    PHP Code:
    <?
    include 'dbconnect.php';



    ?>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    <head>


    </head>

    <body bgcolor="#E0E0E0" background="interface/bg.gif" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
    <table width="465" border="0" cellspacing="0" cellpadding="6">
      <tr>
        <td valign="top" class="title"><table width="100%" border="0" cellpadding="0" cellspacing="0" class="body">
          <tr>
            <td height="22" valign="top"><p class="title">No of current visitors </p></td>
          </tr>
          <tr>
            <td height="45"><div align="justify">
              <?
    session_start
    ();
    $session=session_id();
    $time=time();
    $time_check=$time-500//SET TIME 10 Minute


    $sql="SELECT * FROM user_online WHERE session='$session'";
    $result=mysql_query($sql);

    $count=mysql_num_rows($result);

    if(
    $count=="0"){
    $sql1="INSERT INTO user_online(session, time)VALUES('$session', '$time')";
    $result1=mysql_query($sql1);
    }
    else {
    "$sql2=UPDATE user_online SET time='$time' WHERE session = '$session'";
    $result2=mysql_query($sql2);
    }

    $sql3="SELECT * FROM user_online";
    $result3=mysql_query($sql3);

    $count_user_online=mysql_num_rows($result3);

    echo 
    "User online : $count_user_online "

    // if over 10 minute, delete session 
    $sql4="DELETE FROM user_online WHERE time<$time_check";
    $result4=mysql_query($sql4);

    mysql_close();

    // Open multiple browser page for result
    ?>
            </div></td>
          </tr>
        </table></td>
      </tr>
    </table>

    </body>
    </html>

  2. #2
    SitePoint Evangelist Rodney H.'s Avatar
    Join Date
    Sep 2005
    Location
    Chicago, IL
    Posts
    479
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I would suggest moving your call to start the session to the very top of the page before outputting any HTML and then trying again. That may help things...

    Check the manual: http://www.php.net/session_start

    From PHP.net:

    Note: If you are using cookie-based sessions, you must call session_start() before anything is outputted to the browser.

  3. #3
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    is that only the error in the code
    is the code able to do what it is suppose to do..
    i feel so...
    but that refresh update made me thing it is really not tht advanced script...
    is it logically correct and can do my work...

    thanks for reply
    i will check it...
    any way any comments...?

  4. #4
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Code works fine when i kept session_start() and session_id creating in the first before any thing...

    but one problem with this script i see

    ok i am monitoring every about 8 minutes...

    but in between that if i open mutiple browser and open same page from 2 browser (ie open that page in Interexplorer and again open IE and open that page...)
    the count increase though it is from same computer...

    isn't there any way to monitor this?
    see it is same person using mutiple browser?
    i want the counter not to update its same person using mutiple browser and accessing this page...?

    should i log ip as well...what may be its problem...
    and if i write cookie to user comp may be i need to write then again delete cookie every 8 minutes ..that doesn't sound wise
    any other idea or modification to existing one....

    another problem :even after closing all broswer and when that 8 minutes has elasped i can see some rows in the database ..is there any way to remove those after certain time when file is not active...?

    by the way i see this kind of script keeps database busy if there are 50000 users a day then database will quite busy..will it effect performance..is using this script recommended?

    note :in origial post there is error in line $sql2="UPDATE user_online SET time='$time' WHERE session = '$session'"; i have correct it

  5. #5
    SitePoint Wizard silver trophy
    Join Date
    Mar 2006
    Posts
    6,132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    frank1, the very first thing your script should do is purge the old entrys from the database.
    Code:
    DELETE FROM user_online WHERE time<$time_check
    next, insert this users session into the table. you can insert/update in a single query. declare the `session` field UNIQUE in your database. then you can do this
    Code:
    INSERT INTO user_online(session, time)VALUES('$session', '$time')
    ON DUPLICATE KEY UPDATE time='$time'
    finally, count the sessions.
    Code:
    SELECT COUNT(*) FROM user_online

  6. #6
    play of mind Ernie1's Avatar
    Join Date
    Sep 2005
    Posts
    1,252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is how I use the login and the online features.
    It's not exactly how is on my site, but the online is almost the same, hope it helps.
    Code:
    CREATE TABLE `user_online` (
      `id` varchar(32) NOT NULL default '',
      `user` varchar(12) default NULL,
      `logintm` int(10) default NULL,
      `access` int(10) unsigned default NULL,
      PRIMARY KEY  (`id`)
    );
    
    CREATE TABLE `users` (
      `id` int(11) NOT NULL auto_increment,
      `login` varchar(12) default NULL,
      `pwd` varchar(32) default NULL,
      `lastlogin` datetime default NULL,
      `visits` int(11) unsigned default NULL,
      PRIMARY KEY  (`id`)
    );
    index.php
    PHP Code:
    <?php
    header
    ("Content-type: text/html");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache"); 
    echo 
    "<?xml version=\"1.0\"?>\n"
    echo 
    "<!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\">\n"
    ;
    ?>
    <html>
    <head>
    <title>login</title>
    </head>

    <body>
        <form method="post" action="au.php">
            <b>login:</b> <input name="login" type="text"/><br />
            <b>passwd:</b> <input name="pwd" maxlength="12"/>
        <input type="submit" value="login"/>
        </form>
    </body>

    </html>
    au.php
    PHP Code:
    <?php
    session_start
    ();
    $id=session_id();
    include 
    'opendb.php';
    $login=isset($_POST['login']) ? $_POST['login'] : '';
    $pass=isset($_POST['pwd']) ? $_POST['pwd'] : '';
    $login=strip_tags($login); 
    $pass=strip_tags($pass); 
    $login=str_replace(" ","",$login); 
    $pass=str_replace(" ","",$pass); 
    $login=str_replace("%20","",$login); 
    $pass=str_replace("%20","",$pass);
    $login=mysql_real_escape_string($login);
    $pass=mysql_real_escape_string($pass);
    $pass=md5($pass);
    $req mysql_query("SELECT login,pwd FROM users WHERE pwd='".$pass."' AND login='".$login."'") or die(mysql_error());
    if(
    mysql_num_rows($req)){
    $row mysql_fetch_array($req);
    $user $row['login'];
    $_SESSION['auth'] = 1;
    $_SESSION['user'] = $user;
    mysql_query("DELETE FROM user_online WHERE user = '".$_SESSION['user']."'") or die(mysql_error());
    ?>
    <head>
    <meta http-equiv="content-type"
    content="text/html;charset=utf-8" />
    <meta http-equiv="Refresh" content="1;url=online.php?sid=<?php echo strip_tags(session_id()); ?>" />
    <title><?php echo $_SESSION['user']; ?></title>
    </head>
    <body>
        <p>
        <?php
        
    echo "Welcome, ".$_SESSION['user']."!<br />";
        
    ?>    
        </p>
          <a href="online.php?sid=<?php echo strip_tags(session_id()); ?>">
            click here if your browser dose not automatically redirect you 
          </a>
    </body>
    </html>
    <?php }else{ ?>
    <html>
    <head>
    <title>login</title>
    </head>
    <body>
            <p align="center">
            login failed. please try again<br />
        </p>
        <form method="post" action="au.php">
            <b>login:</b> <input name="login" type="text"/><br />
            <b>passwd:</b> <input name="pwd" maxlength="12"/>
        <input type="submit" value="login"/>
        </form><br />
    </body>
    </html>
    <?php
    $_SESSION
    ['auth'] = false;
    $_SESSION['user'] = false;
    session_unset();
    session_destroy();
    }
    ?>
    fun.php (functions)
    PHP Code:
    <?php
    function update_user_online(){
      
    $sid=session_id();
      
    $ac=time();
      
    $user=$_SESSION['user'];
      
    $onl mysql_query("SELECT user FROM user_online WHERE user='$user'") or die(mysql_error());
      if(
    mysql_num_rows($onl) ==0){
      return 
    mysql_query("INSERT INTO user_online SET id='$sid' , user='$user' , logintm=$ac , access=$ac") or die(mysql_error());
      }
      return 
    mysql_query("UPDATE user_online SET access=$ac WHERE id='$sid'") or die(mysq_error());
    }

    function 
    clean_user_online(){
     
    $user=$_SESSION['user'];
     
    $timeout=time()-3600;
     
    mysql_query("DELETE FROM user_online WHERE access<$timeout") or die(mysql_error());
     if(
    mysql_affected_rows()){
     
    mysql_query("UPDATE users SET lastlogin=now() , visits=visits+1 WHERE login='$user'") or die(mysql_error());
     }
    }
    ?>
    online.php
    PHP Code:
    <?php 
    session_start
    ();
    if(!isset(
    $_SESSION['auth'])){
    header("Location: index.php");
    $_SESSION['auth'] = false;
    session_unset();
    exit(
    0);
    }
    include(
    "opendb.php");
    include(
    "fun.php");
    clean_user_online();
    update_user_online();
    $sid=session_id();
    $login=$_SESSION['user'];
    $timeout=time()-150;
    header("Content-type: text/html");
    header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
    header("Last-Modified: " gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache"); 
    echo 
    "<?xml version=\"1.0\"?>\n"
    echo 
    "<!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\">\n"
    ;
    $q "SELECT user_online.user, user_online.access, users.login FROM user_online 
            INNER JOIN users 
            ON users.login = user_online.user 
            WHERE user_online.access >= 
    $timeout ";
    $q_result mysql_query($q,$db) or die(mysql_error());
    $n mysql_num_rows($q_result);
    if (
    mysql_num_rows($q_result) == 1){
    $x "user";
    }else{
    $x "users";
    }
    if(isset(
    $_GET['p']) AND ($_GET['p'] != '' && $_GET['p'] != ' ')){
       
    $pageNum = (int) $_GET['p'];
       if(!
    eregi("^[0-9]+$",$pageNum)){
       
    $pageNum 1;
       }
       
    $pageNum trim($pageNum); 
       }else{ 
       
    $pageNum 1
       }
    if(isset(
    $_GET['q']) AND ($_GET['q'] != '' && $_GET['q'] != ' ')){
       
    $q = (int) $_GET['q'];
       if(!
    eregi("^[0-9]+$",$q)){
       
    $q 10;
       }
       
    $q trim($q); 
       }else{ 
       
    $q 10
       }
    $offset = ($pageNum 1) * $q;
    $query "SELECT user_online.user, user_online.logintm FROM user_online 
            INNER JOIN users 
            ON users.login = user_online.user 
            WHERE user_online.access >= 
    $timeout ";
    $pagingQuery "LIMIT $offset$q";
    $result mysql_query($query $pagingQuery) or die(mysql_error());
    $oslt  mysql_query($query) or die(mysql_error());
    $onum mysql_num_rows($oslt);
    $omax ceil($onum/$q);
    if (
    $pageNum >= && ($pageNum <= $omax))
    {
        
    $p $pageNum;

    }else{

        
    $p 1;

    }
    $num=isset($_GET['c']) ? (int) $_GET['c']+1;
    if(
    $num 1000){
    $num mt_rand(5,99999);
    }
    ?>
    <head>
    <meta http-equiv="content-type"
    content="text/html;charset=utf-8" />
    <meta http-equiv="Refresh" content="20;url=online.php?p=<?php echo $p ?>&amp;q=<?php echo $q ?>&amp;c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>" />
    <title>users</title>
    </head>

    <body>

    <?php 
    if ($pageNum >= && ($pageNum $omax))
    {
        
    $p $pageNum 1;
    ?>

    <a href="online.php?p=<?php echo $p ?>&amp;q=<?php echo $q ?>&amp;c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>">
    next
    </a>
    <?php }?>
    <?php 
        
    if ($pageNum && ($pageNum <= $omax))
    {
        
    $p $pageNum 1;
    ?>
    <a href="online.php?p=<?php echo $p ?>&amp;q=<?php echo $q ?>&amp;c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>">
    prev
    </a>
    <?php }?>
        <p align="center">
        <br />
    <?php 
    echo "
        online 
    $n $x<br />\n";
        while(
    $m mysql_fetch_array($result)){
        
    $u=$m['user'];
    $olntime "SELECT user_online.user, user_online.logintm FROM user_online 
            INNER JOIN users 
            ON users.login = user_online.user 
            WHERE user_online.access >= 
    $timeout AND user_online.user='$u' ";
    $olntime_result mysql_query($olntime) or die(mysql_error());
    while(
    $oltm mysql_fetch_array($olntime_result)){
    $act time();
    $lgnt $oltm['logintm'];
    $dif $act $lgnt;
    $min floor($dif/60);
    $sec $dif%60;
    if(
    strlen($sec) == 1){
    $sec "0".$sec;
    }
    $tlim " [$min:$sec]";
    }
        echo 
    $u." ".$tlim."<br />\n";

    }
    $result  mysql_query($query,$db) or die(mysql_error());
    $numrows mysql_num_rows($result);
    $maxPage ceil($numrows/$q);
    if (
    $pageNum && (!($pageNum $maxPage)))
    {
        
    $p $pageNum 1;

    ?>
        <a title="&lt;&lt;" href="online.php?p=<?php echo $p ?>&amp;q=<?php echo $q ?>&amp;c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>">&lt;&lt;</a>
        <a title="top" href="online.php?c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>">top</a>
    <?php 
    }
    if (
    $pageNum $maxPage)
    {
        
    $p $pageNum 1;

    ?>
        <a title="&gt;&gt;" href="online.php?p=<?php echo $p ?>&amp;q=<?php echo $q ?>&amp;c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>">&gt;&gt;</a>  
    <?php 
    }
    else
    {
    $p 1;
    }
    if(
    $pageNum $maxPage){?>
        <a title="&gt;&gt;" href="online.php=<?php echo $p ?>&amp;q=<?php echo $q ?>&amp;c=<?php echo $num ?>&amp;sid=<?php echo $sid ?>">&lt;&lt;</a>
    <?php }?>
        </p>

    </body>
    </html>
    and the logout.php
    PHP Code:
    <?php
    session_start
    ();
    $sid=session_id();
    require_once(
    "opendb.php");
    mysql_query("DELETE FROM user_online WHERE `id`='$sid'") or die(mysql_error());
    unset(
    $_SESSION['auth']);
    unset(
    $_SESSION['user']);
    $_SESSION=array();
    session_destroy();
    header("Location:index.php");
    exit(
    0);
    ?>
    Last edited by Ernie1; Oct 16, 2006 at 06:08. Reason: added logout feature
    my mobile portal
    ghiris.ro

  7. #7
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    edited
    Last edited by frank1; Oct 8, 2006 at 21:43.

  8. #8
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Sorry initially i didnt noticed that clamcluster
    DELETE FROM user_online WHERE time<$time_check
    i have that line ...do you mean that ,that should come first before entering /updating data?

    by the way creating session is from php..i have found it generates unique session_id every time...but two different session_id if we

    open two browser window...at same time...


    new code which seems to work fine,considering multiple browser windows from same computer...
    PHP Code:
    $time=time();
    $time_check=$time-400//SET TIME 8 Minute

    $sql4="DELETE FROM user_online WHERE time<$time_check";
    $result4=mysql_query($sql4);
    // if over 8 minute, delete session 

    $ip $_SERVER['REMOTE_ADDR']; 

    $sql="SELECT * FROM user_online WHERE session='$session' and ip like \"$ip\"";
    $result=mysql_query($sql);

    $count=mysql_num_rows($result);

    if(
    $count=="0"){
    $sql1="INSERT INTO user_online(session, time ,ip)VALUES('$session', '$time','$ip')";
    $result1=mysql_query($sql1);
    }
    else {
    $sql2="UPDATE user_online SET time='$time' WHERE session = '$session' and ip like \"$ip\"";
    $result2=mysql_query($sql2);
    }

    $sql3="SELECT * FROM user_online";
    $result3=mysql_query($sql3);

    $count_user_online=mysql_num_rows($result3);

    echo 
    "User online : $count_user_online "


    But last time i used that $ip = $_SERVER['REMOTE_ADDR']; it gave very mis reading in my form ...when i was using it to insert ip in

    form ..same ip was being entered though the form was submitted from different location..
    so i always fear using it...
    will it do what i am looking for
    any glitch you see.....pitfalls...?

    one pitfall i see when using ip is if there are many user or computer in network may be using proxies they will have same public ip that way user wont be updated...

    thanks for all replies

  9. #9
    SitePoint Wizard silver trophy
    Join Date
    Mar 2006
    Posts
    6,132
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    yeah an ip address is not a unique identifier. youre correct, people behind a proxy(which is more common then many people think) may share the same ip address.

    as far as requesting the same page from 2 browser windows at the same time:
    its possible 2 session ids will be issued, but the browser will only retain the last session id. this is a race condition that i dont see an easy fix for, although i also dont see it happening very often. this shouldnt happen though unless you try really hard to open the page in both windows exactly at the same time. i think the possibility of this is very low, and it shouldnt be a big deal if your numbers are inflated for 8 minutes until you wipe the old session id clean from the db.

    2 session ids will always be issued(and kept) if you have 2 different browsers open(eg firefox and IE), because cookies are stored by the browser, and browsers dont check each others cookies.

    again, i would use a single query for the insert/update like i said in my first post. otherwise you are creating an additional race condition, not to mention the wasteful use of another query.

    see the querys i posted for you. they are much more efficient than what you are currently doing.

  10. #10
    SitePoint Wizard frank1's Avatar
    Join Date
    Oct 2005
    Posts
    1,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by clamcrusher

    again, i would use a single query for the insert/update like i said in my first post. otherwise you are creating an additional race condition, not to mention the wasteful use of another query.

    see the querys i posted for you. they are much more efficient than what you are currently doing.
    is that really that big issue ..i feel that if else condition almost does the same...
    what kind of race condition
    does that line replace
    these all
    PHP Code:
    $sql="SELECT * FROM user_online WHERE session='$session' and ip like \"$ip\""
    $result=mysql_query($sql); 

    $count=mysql_num_rows($result); 

    if(
    $count=="0"){ 
    $sql1="INSERT INTO user_online(session, time ,ip)VALUES('$session', '$time','$ip')"
    $result1=mysql_query($sql1); 

    else { 
    $sql2="UPDATE user_online SET time='$time' WHERE session = '$session' and ip like \"$ip\""
    $result2=mysql_query 
    i think i still have to make first select...
    any way thanks


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •