Activity Stream
48,167 MEMBERS
6721 ONLINE
besthostingforums On YouTube Subscribe to our Newsletter besthostingforums On Twitter besthostingforums On Facebook besthostingforums On facebook groups

Results 1 to 7 of 7

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1.     
    #1
    Member
    Website's:
    litewarez.net litewarez.com triniwarez.com

    Lightbulb Tutorial: Creating a users online script in PHP5

    Heya, im a little board at the moment so might as well share some knowledge lol.


    This is how you create a Users Online Class in PHP5:

    Step 1.
    Firstly we need to create a database to hold the information within, the code below would be executed within PhpMyAdmin or what ever MySql Software you are using

    Code: 
    CREATE TABLE IF NOT EXISTS `usersonline` (
    	`id` int(10) NOT NULL AUTO_INCREMENT,
    	`ip` varchar(15) NOT NULL,
    	`location` varchar(512) NOT NULL DEFAULT '/',
    	'timestamp` varchar(15) NOT NULL DEFAULT '',	
    	UNIQUE KEY `id` (`id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2231 ;
    Step 2.
    Ok so lets begin by create the class structure

    PHP Code: 
    <?php
        
    class usersonline{
        }
    ?>
    What this has done is basically created an object in witch you can use throught your site. (an object holds several methods and the methods are whats used to do different task.)

    Step 3.
    Assigning some variables to hold some temporary data

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }
    ?>
    Step 4.
    in this step were going to create a function thats know as a constructor, what this means is that when you first initiate the class this function will run to to prepare any data before you actually use the class
    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
        
    }
    ?>
    Step 5.
    As you can see from the above code we have created a construct method, now we tell the class what to do when its first called

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
            
    $this->time time();    //$this->time is a reference to var $time..
        
    }
    ?>
    Step 6.

    Ok the class should construct now and what we need to do is to create some methods/functions so we will begin with the function that gets the IP address.

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
            
    $this->time time();    //$this->time is a reference to var $time..
        
    }

        public function 
    getIp(){
            
    $this->ip $_SERVER['REMOTE_ADDR'];
        }
    ?>
    Ok so when we run the getIp() function this will assign the var $ip with the IP address contained in $_SERVER

    Step 7.
    here we will create another function that will get the location of the user.

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
            
    $this->time time();    //$this->time is a reference to var $time..
        
    }

        public function 
    getIp(){
            
    $this->ip $_SERVER['REMOTE_ADDR'];
        }
        
        public function 
    getLocation(){
            
    $this->location $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
            
    //This should be something like (index.php?page=2)
        
    }
    ?>
    Step 8.
    Ok now we have created all the methods/functions we need for the __constructor we can now update the constructor function

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
            
    $this->time time();    //$this->time is a reference to var $time..
            //When we run what of the functions it will auto fill the Variables
            
    $this->getIp();
            
    $this->getLocation();
        }

        public function 
    getIp(){
            
    $this->ip $_SERVER['REMOTE_ADDR'];
        }
        
        public function 
    getLocation(){
            
    $this->location $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
            
    //This should be something like (index.php?page=2)
        
    }
    ?>
    Step 9.

    Ok no when we instantiate the object it will automatically track the time,ip.location before we run any methods/functions

    But below were going to create 2 primary functions that will furfill the main perpose of the script, they are:
    • Update the MySql Table
    • Return the count of users online


    Step 9.1

    Here were going to update the table with a method

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
            
    $this->time time();    //$this->time is a reference to var $time..
            //When we run what of the functions it will auto fill the Variables
            
    $this->getIp();
            
    $this->getLocation();
        }

        public function 
    getIp(){
            
    $this->ip $_SERVER['REMOTE_ADDR'];
        }
        
        public function 
    getLocation(){
            
    $this->location $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
            
    //This should be something like (index.php?page=2)
        
    }

        public function 
    update(){
            
    $time_distance = ($this->timeout $this->time);
            
    $sql_query "DELETE FROM useronline WHERE timestamp < ".$time_distance;
            
            
    //Ok so now we have an sql string we will run the SQL
            
            
    mysql_query($sql_query);
        }
    ?>
    Step 9.2

    Ok so by now we have update the table and we want to be able to get the LATEST data from mysql witch will tell us how many UNIQUE users we have online

    PHP Code: 
    <?php
        
    class usersonline{
            
            var 
    $timeout    7200;    //this is the time you want to track  your users back to
            
    var $ip        false;    // The ip address of the user
            
    var $location    false;    //The location within your site you want to track
            
    var $time        false;    //This will just hold the current time
        
    }

        function 
    __construct(){
            
    //Here we will prepare data
            
    $this->time time();    //$this->time is a reference to var $time..
            //When we run what of the functions it will auto fill the Variables
            
    $this->getIp();
            
    $this->getLocation();
        }

        public function 
    getIp(){
            
    $this->ip $_SERVER['REMOTE_ADDR'];
        }
        
        public function 
    getLocation(){
            
    $this->location $_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
            
    //This should be something like (index.php?page=2)
        
    }

        public function 
    update(){
            
    $time_distance = ($this->timeout $this->time);
            
    $sql_query "DELETE FROM useronline WHERE timestamp < ".$time_distance;
            
            
    //Ok so now we have an sql string we will run the SQL
            
            
    mysql_query($sql_query);
        }

        function 
    totalOnline(){
            
    $count = @mysql_num_rows mysql_query("SELECT DISTINCT ip FROM useronline"));
        }
    ?>
    Ok so this function is basicaly calculating how many UNIQUE ip hits have been inserted into the data within the above timeframe.

    Step 10
    Ok so now the class is finally complete we can safe that into a php file now and name it usersonline.class.php and upload it to your server!


    Step 11

    Ok so now you want to get the count into your files, we will use the index file for example..

    Open your index.php file or whatever file your adding this too and add the following block of code

    PHP Code: 
    <?php

    include 'path/to/usersonline.class.php';

    /*
        * :: Just a not you must be connected to the database before you call the class methods!!!
    */

    //Assuming connected..

    $usersonline = new usersonline;    
    /*
        * Ok now as we run this line of code what ever
        * was in the __construct will be auto run!
    */

    //Ok we need to make sure that we run the update method to clean the amount of users up.

    $usersonline->update(); // ok that should of cleaned tho rows up!

    //Now we can add this to the out body for HTML
    ?>
    <html>
        <head>
            <title>Uses online by Litewarez!</title>
        </head>
        <body>
            <!-- your usual body here -->
            <div class="usersonline">We have <?php echo $usersonline->totalOnline(); ?></div>
        </body>
    </html>
    Ok now everything should be finished and i hope you enjoyed the tutorial.

    P.S. Stay Warez
    litewarez Reviewed by litewarez on . Tutorial: Creating a users online script in PHP5 Heya, im a little board at the moment so might as well share some knowledge lol. This is how you create a Users Online Class in PHP5: Step 1. Firstly we need to create a database to hold the information within, the code below would be executed within PhpMyAdmin or what ever MySql Software you are using CREATE TABLE IF NOT EXISTS `usersonline` ( Rating: 5
    Join Litewarez.net today and become apart of the community.
    Unique | Clean | Advanced (All with you in mind)
    Downloads | Webmasters


    Notifications,Forum,Chat,Community all at Litewarez Webmasters


  2.   Sponsored Links

  3.     
    #2
    Respected Developer
    Website's:
    X4B.org
    Gee it would really be a shame If I shared my 10 line solution, though I have added more since that adds support for multiple sites.

    Anyway nice tutorial, possibly a little bit to complecated for the average user here and I see you love your OOP. Anyway nice, and keep up the good work.

  4.     
    #3
    Member
    Website's:
    litewarez.net litewarez.com triniwarez.com
    yea i can do a users online in that aswell i just tried to build it with all the very basic OOP factors for the users too learn.. if they dont know it the only way there going to learn is by attempting the things they do not know !
    Join Litewarez.net today and become apart of the community.
    Unique | Clean | Advanced (All with you in mind)
    Downloads | Webmasters


    Notifications,Forum,Chat,Community all at Litewarez Webmasters


  5.     
    #4
    Respected Developer
    Website's:
    X4B.org
    I suppose you can look at it that way.

    Just thought I would make some people cream lol, nah the codes not that sexy yet.

    Code: 
    function users_online(){
        $res = mysql_query('SELECT COUNT(*) FROM users_online WHERE ip='.ip2long($_SERVER['REMOTE_ADDR']));
        $row = mysql_fetch_array($res,MYSQL_NUM);
        if(!$row[0]){
            mysql_query('INSERT INTO users_online VALUES('.ip2long($_SERVER['REMOTE_ADDR']).','.time().')');
        }else{
            mysql_query('UPDATE users_online SET timer='.time().' WHERE ip='.ip2long($_SERVER['REMOTE_ADDR']));
        }
        $res = mysql_query('SELECT * FROM users_online WHERE timer>'.(time()-(60*10)));
        if(!$res){
            return '0';
        }
        return mysql_numrows($res);    
    }

    you really should ip2long decreases the size of the sql table needed to store the data and means that it can do int comparson compared to string comparison which is much slower.

  6.     
    #5
    Member

    thanks for this

    in 5th line of sql
    it should be
    PHP Code: 
        `timestampvarchar(15NOT NULL DEFAULT '/'
    Coding Horror Fan
    I don't read PM's frequently .

  7.     
    #6
    The Wise One
    Website's:
    twilight.ws ddlrank.com
    Relevant bump:

    Ive been looking for a script like this but thing what I do not get is why this all happens MySQL based? It's very slow and inneficient for managing the users online in a database.
    Using sessions / file-based would be so much faster + more efficient.
    I can always be contacted by sending a tweet @twilightws

  8.     
    #7
    Member
    Website's:
    litewarez.net litewarez.com triniwarez.com
    The reason its mysql based is due to the face that its meant to be used with user tracking and login systems... if you add a user id to the tracker table you can do a RIGHT JOIN in sql to check see when that user is online and last ip etc...

    helps with users online AND registered users online !


    i do this within Litewarez Webmasters to track what webmasters are active in the chat by scanning sql rows with user id and time less that 3 min ago also with the location file as /webmasters/chat.php

    this helps in that way

    --

    Quote Originally Posted by desiboy View Post

    thanks for this

    in 5th line of sql
    it should be
    PHP Code: 
        `timestampvarchar(15NOT NULL DEFAULT '/'
    Not really, the reason the location has a default of / is that its a URI and therefore if its not set then we do the default of / witch in location terms means root.

    if anything the timestamp should be an `timestamp` interger(15) NOT NULL DEFAULT 0,
    Join Litewarez.net today and become apart of the community.
    Unique | Clean | Advanced (All with you in mind)
    Downloads | Webmasters


    Notifications,Forum,Chat,Community all at Litewarez Webmasters


Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Similar Threads

  1. Users online script
    By pi0tr3k in forum Webmaster Resources
    Replies: 4
    Last Post: 1st Jun 2009, 08:26 PM
  2. PHP Tutorial (Creating Classes)
    By litewarez in forum Tutorials and Guides
    Replies: 0
    Last Post: 14th May 2009, 11:40 AM
  3. PHP Tutorial ( Creating Functions ).
    By litewarez in forum Tutorials and Guides
    Replies: 9
    Last Post: 12th May 2009, 04:26 PM
  4. Tutorial - Creating Signatures in Photoshop
    By rich5lee in forum Tutorials and Guides
    Replies: 0
    Last Post: 28th Jul 2008, 05:14 PM
  5. Simple PHP Users Online Script
    By Whoo in forum Webmaster Resources
    Replies: 0
    Last Post: 9th Jun 2008, 10:10 AM

Tags for this Thread

BE SOCIAL