View currently online users (with a database table) (v8)

Tips submitted by PHPMaker users
Post Reply
adim

View currently online users (with a database table) (v8)

Post by adim »

Hi,
I've initially posted this on another topic here, but i thought this can have it's own topic. So here it is.

There is another way to see active users conected.
You need the following:

  1. We will make a new table into your database, lets say: users_online with following definition

    DROP TABLE IF EXISTS `mydatabase`.`users_online`;
    CREATE TABLE `mydatabase`.`users_online` (
    `timestamp` int(15) NOT NULL DEFAULT '0',
    `ip` varchar(40) NOT NULL,
    `file` varchar(100) NOT NULL,
    `username` varchar(32) DEFAULT NULL,
    `updated` timestamp NULL DEFAULT NULL,
    PRIMARY KEY (`timestamp`),
    KEY `ip` (`ip`),
    KEY `username` (`username`)
    ) ENGINE=MEMORY DEFAULT CHARSET=utf8;

    We make it MEMORY table because there will be a lot of insert/deletes in this table and depending of how many users will be connected, you dont want to put overhead on your HDD.

  2. We need a page that will be loaded with every time together with any page on your site, like header or footer. Lets say header.php, so modify your header.php and put this code somewhere:

    <?php
    // Display no of users online to Administrator //
    
    $timeoutseconds = 600; // = 10 minutes (this is the timeout set in config file | after this period my app will automatically logout user, you can put here any period)
    
    $timestamp = time();
    $timeout = $timestamp-$timeoutseconds;
    
    if (!isset($_SESSION["mydatabase_status_UserName"])) $_SESSION["mydatabase_status_UserName"] = "Unknown User"; // this is set automatically by phpmkr on login time
    
    $insert = "INSERT INTO users_online VALUES ('".$timestamp."','".$_SERVER["REMOTE_ADDR"]."','".$_SERVER["PHP_SELF"]."','".$_SESSION["mydatabase_status_UserName"]."',NOW())";
    $resultIns = $conn->execute($insert);
    if(!($resultIns)) {
    print "Useronline Insert Failed > ";
    }
    $delete = "DELETE FROM users_online WHERE timestamp < '".$timeout."'";
    $resultDel = $conn->execute($delete);
    if(!($resultDel)) {
    print "Useronline Delete Failed > ";
    }
    
    $select = "SELECT timestamp FROM users_online GROUP BY username ";
    $resultSel = $conn->execute($select);
    if(!($resultSel)) {
    print "Useronline Select Error > ";
    }
    $user = $resultSel->RecordCount();
    
    $resultSel->close();
    
    //Display only to Administrators
    if (IsSysAdmin()) {
    if($user == 1) {
    print("<b style=\"color:red;\">".$user."</b> user online (You)\n");
    } else {
    print("<b style=\"color:red;\">".$user."</b> users online &nbsp;|&nbsp;<a href=\"home.php\" ><img src=\"images/view-online-users.png\" width=\"16px\" height=\"16px\" border=\"0\" align=\"absmiddle\" title=\"View online users\" /></a>\n");
    }
    } // end if Admins
    
    ?>

    It shows you how many users are conected on your site within a timespan of $timeout (in our case 10 minutes would be sufficient).
    I've also made a new page to show me their usernames along with other details.
    So make a new page called home.php
    I made this page available only to Administrator too. Code for this page can be:

    <?php
    if (session_id() == "") session_start(); // Initialize Session data
    
    include_once "ewcfg8.php";
    include_once "ewmysql8.php";
    include_once "phpfn8.php";
    include_once "usersinfo.php"; // <table>info.php of your user table
    include_once "userfn8.php";
    ?>
    <html>
    <body>
    
    <h2>USERS ONLINE</h2>
    <p>
    See users currently online (timespan - 600s = 10 min ).
    </p>
    <span style="font-size:small;">
    <?php 
    $select = "SELECT uo.username, uo.file FROM users_online uo GROUP BY uo.username ORDER BY uo.updated DESC";
    $result = $conn->execute($select);
    echo "Currently online users: <br>";
    
    while(!$result->EOF) {
    echo "&nbsp;|&nbsp;".$result->fields[0] . "&nbsp;(".$result->fields[1].")&nbsp;<br>";    //shows username and the script (or page) which user has been visited or clicked last time (in 10 min span)
    $result->MoveNext();
    } //end while
    ?>
    </span>
    <hr />
    </body>
    </html>

    NOTE:
    For those who wants the logs should not be refreshed (deleted) every 10 min, suppress the DELETE SQL, and be sure you made the users_online table ENGINE=MYISAM or InnoDB on HDD.
    Maybe you don't want this because from my experience in my app i had around 300 users and there are thousands of hits per day, the table is growing fast, besides, phpMaker has a very good audittrail system you can count on it.

Of course you can modify script to show you different things, like in my case it shows me the company user belongs or IP they are connected from, along with their email addresses and last time they were logged in before this.

That's all, hope this help.
Enjoy.
adim


cruzz

Post by cruzz »

Hi adim... Thank you so much for your tips...

I just wanna share a small improvement..

Changing a lil bit the Query and taking the last TIMESTAMP, we can always display the current FILE that the user is using...

SELECT uo.username, uo.file, uo.ip, uo.updated
FROM users_online uo
INNER JOIN (
SELECT username, MAX( TIMESTAMP ) AS MaxTimeStamp
FROM users_online
GROUP BY username
) groupedtt ON uo.username = groupedtt.username
AND uo.timestamp = groupedtt.MaxTimeStamp

Regards


shahparz

Post by shahparz »

That's a very good script.

i have two problems, i am facing.

  1. i don't have file "usersinfo.php".

  2. i am seeing only "Unknown User". Why ?

Please help.


adim

Post by adim »

Hi shahparz, thank you.

File "usersinfo.php" refers to a page which is your users table info page... User table is where you keep your usernames, userIDs, so on...
What is the name of your users table?

For example: if your user table is named "employee", in this case your page will be employeeinfo.php

adim


shahparz

Post by shahparz »

i understand it after a while. Thanks again very much.


merlin
User
Posts: 14

Post by merlin »

Does this work with v10 - I still get Unkown User in users_online table

mysql> select * from users_online;
+----------------+----------------+--------------------------------------------+------------------+--------------------------+
| timestamp | ip | file | username | updated |
+----------------+----------------+--------------------------------------------+------------------+--------------------------+
| 1375105493 | 88.148.89.37 | /pots_bme/eu2Dm012Dt14edit.php | Unknown User | 2013-07-29 14:44:53 |
| 1375105222 | 88.148.89.37 | /pots_bme/eu2Dm012Dt14list.php | Unknown User | 2013-07-29 14:40:22 |
| 1375105217 | 88.148.89.37 | /pots_bme/eu2Dm012Dt14edit.php | Unknown User | 2013-07-29 14:40:17 |
| 1375105161 | 88.148.89.37 | /pots_bme/eu2Dm012Dt14edit.php | Unknown User | 2013-07-29 14:39:21 |
+---------------+------------------+-------------------------------------------+------------------+--------------------------+

Regards
Martyn


merlin
User
Posts: 14

Post by merlin »

I think I narrowed this down to this session variable

if (!isset($SESSION["mydatabase_status_UserName"])) $SESSION["mydatabase_status_UserName"] = "Unknown User";

I cannot find this anywhere - am I just plain dumb or should "mydatabase_status_UserName" be changed to something else !!

Regards
MArtyn


merlin
User
Posts: 14

Post by merlin »

Apologies to all - I am rather dumb.

$_SESSION["mydatabase_status_UserName"] is a specific session vaiable that is created when you save the description of your project

To find all variables SESSION,GET,PUT & FILES that are passed i use this peice of code at the top of my pages.

// UN-Comment  when you run the code in debug
/* 
    while ($var = each($_SESSION)) {
      printf ("Key <b>%s</b> has the value of: <b>%s</b><br>", $var['key'], $var['value']);
    }

    echo  "Start SESSION values <br>";
    print("<pre>");
    print_r($_SESSION);
    print("</pre>");
    echo  "END SESSION values <br>";

    echo  "Start GET values <br>";
    print("<pre>");
    print_r($_GET);
    print("</pre>");
    echo  "END   GET values <br>";
    echo  "Start POST values <br>";
    print("<pre>");
    print_r($_POST);
    print("</pre>");
    echo  "End   POST values <br>";
    echo  "Start FILES values <br>";
    print("<pre>");
    print_r($_FILES);
    print("</pre>");
    echo  "End FILES values <br>";
*/

Post Reply