<?php
/*

Class counter:    09 January 2002

Author:            Duncan Gough

Overview:        A basic session counter for display on your home page.
                A session is defined as an ip address with a referring url of your website (e.g. http://www.suttree.com/).

Installation:    Decompress the files into a folder called counter in your webroot.
                Modify the line that reads 'var $website = "http://yourwebsite.co.uk";' so that yourwebsite.co.uk is replaced with your own URL.

                Counter requires a MySQL database in which to store hits. Create a table called counter and one called counter_sessions by executing the following SQL code;

                # Table counter
                CREATE TABLE counter (
                  ID int(4) NOT NULL auto_increment,
                  ip_address varchar(15),
                  last_active int(25),
                  PRIMARY KEY (ID)
                );
                CREATE INDEX counter_total ON counter(ID);

                # Table counter_sessions
                CREATE TABLE  counter_sessions (
                  ID int(4) NOT NULL auto_increment,
                  session_id varchar(100) NOT NULL,
                  ip_address varchar(15),
                  referrer varchar(255),
                  page varchar(255),
                  last_active int(25),
                  PRIMARY KEY (ID)
                );
                CREATE INDEX session_search ON counter_sessions(session_id);

Usage:            To activate the counter code, add the following few lines of PHP to your homepage.
                Note, the counter code expects a variable called $link_id to be present, as it uses that as a link indentifier to the MySQL database.
                Also, since a database connection is required, you must include or set up that connection before including the counter code, as below;

                <?php
                // pull in our include files
                include("/path/to/your/database/connection/file/here");

                // establish a database connection
                $link_id = connect();

                // now activate the counter object
                include("counter/counter.php");
                $counter = new counter();

                // Rest of your homepage goes here

                ?>

                That's all there is to it - the line $counter = new counter(); will do everything for you.
                Next, just add this HTML code to any page you want the counter to appear on...

                <script language="JavaScript" src="./counter/counter.js">

                ...and that's it. Test the code by viewing your homepage and hopefully you should see a line like 'Visitor: 1' appear on your page.
*/

class counter {

    
// Modify this to reflect your own URL
    
var $website "http://yourwebsite.co.uk";

    function 
counter() {
        global 
$link_id;

        
// create a session
        
session_start();

        
// check the session, if the referrer is within our site, and the last_active timestamp is within 30 minutes,
        // then do not update the counter table, otherwise, add another hit to the counter table
        
$this->_check_session();

        
// get the num of hits from the counter table, and display it.
        
$sql     "SELECT count(ID) AS count FROM counter";
        
$result $this->_query$sql );
        
$count     = @mysql_result$result0'count' );

        
// write the figure to a flat text file
        
$string "document.write('<font color=\"black\">Visitor: $count</font>')";
        
$fp     fopen("counter/counter.js""w");
        
fputs$fp"$string" );
        
fclose$fp );

        return 
1;
    } 
//endfunc counter

    
function _check_session() {
        global 
$REMOTE_ADDR,$PHP_SELF,$HTTP_REFERER,$link_id;

        
// if the referer is from your website, skip,
        // if $last_active is within last 30 mins, update the session table,
        // otherwise, add to the counter table as it's a brand new, never before seen user (or they haven't been back in the last 30 minutes)
        
$session_id     session_id();
        
$referrer         $HTTP_REFERER;            // referring url
        
$ip_address     $REMOTE_ADDR;                // the ip
        
$page             $PHP_SELF;                // script filename
        
$now             time();                    // unixtime
        
$timeout         = (60*30);                    // 30 mins of unixtime

        // first, check the referer, if its from our domain, then update the counter_sessions table,
        // otherwise, add them to the counter
        
if( ereg$this->website,$referrer ) )    {

            
// The user is from within our domain, so just update the session tables accordingly...

            // first, get the most recent active session (i.e. within the last half hour)
            
$sql     "SELECT id from counter_sessions where session_id = '$session_id' and last_active >= ($now - $timeout)";
            
$result $this->_query($sql);

            
$num_rows = @mysql_num_rows($result);
            if( 
$num_rows )    {

                
// abort - too many active sessions
                
$sql     "UPDATE counter_sessions set last_active = 0 WHERE session_id = '$session_id'";
                
$result $this->_query($sql);

                
// create a new session and store it
                
session_start();

                
$session_id session_id();
                
$sql         "INSERT INTO counter_sessions (session_id, ip_address,referrer,page,last_active) VALUES ('$session_id','$ip_address','$referrer','$page',$now)";
                
$result     $this->_query($sql);

                
// return 0 to indicate a new session was started
                
return 0;

            } elseif( 
$num_rows == )    {

                
// The ideal situation, update the session table, (but not the counter table) and return 1

                // setting last_active to NULL, because it is a timestamp column, will update to the current time...
                
$sql     "UPDATE counter_sessions set last_active = $now where session_id = '$session_id'";
                
$result $this->_query($sql);

                return 
0;

            } else    {

                
// The user is from within our domain, but has been browsing longer than 30 minutes,
                // so create a new session entry, *and* add them to the counter table
                
$sql     "INSERT INTO counter_sessions (session_id, ip_address,referrer,page,last_active) VALUES ('$session_id','$ip_address','$referrer','$page',$now)";
                
$result $this->_query$sql );

                
$sql     "INSERT INTO counter (ip_address,last_active) VALUES ('$ip_address',$now)";
                
$result $this->_query$sql );

                return 
1;

            } 
// endelse

        
} else    {

            
// The user may have just refreshed the page, so double check the counter_session table
            
$sql     "SELECT id from counter_sessions where session_id = '$session_id' and last_active >= ($now - $timeout)";
            
$result $this->_query$sql );

            
$num_rows = @mysql_num_rows$result );

            if( 
$num_rows )    {

                
// abort - too many active sessions
                
$sql     "UPDATE counter_sessions set last_active = 0 WHERE session_id = '$session_id'";
                
$result $this->_query$sql );

                
// now create new session
                
session_start();

                
$session_id session_id();
                
$sql         "INSERT INTO counter_sessions (session_id, ip_address,referrer,page,last_active) VALUES ('$session_id','$ip_address','$referrer','$page',$now)";
                
$result     $this->_query$sql );

                
// return 0 to indicate a new session was started
                
return 0;

            } elseif( 
$num_rows == )    {

                
// The ideal situation, update the session table, (but not the counter table) and return 1

                // setting last_active to NULL, because it is a timestamp column, will update to the current time...
                
$sql     "UPDATE counter_sessions set last_active = $now where session_id = '$session_id'";
                
$result $this->_query$sql );

                return 
0;

            } else    {

                
// We have a brand new visitor, so add him/her to the session table, and increment the counter table
                
$sql     "INSERT INTO counter_sessions (session_id, ip_address,referrer,page,last_active) VALUES ('$session_id','$ip_address','$referrer','$page',$now)";
                
$result $this->_query$sql );

                
$sql     "INSERT INTO counter (ip_address,last_active) VALUES ('$ip_address',$now)";
                
$result $this->_query$sql );

                return 
1;

            } 
// endelse

        
// endelse

    
// endfunc _check_session

    
function _query$sql )    {
        global 
$link_id;

        
$result = @mysql_query$sql,$link_id );

        if( !
$result )    {

            
// Very basic error checking - you'll probably want to replace
            // this with your own error-handling functions
            
echo "Error: ".$sql;

        }    else    {

            return 
$result;

        } 
//endif

    
// endfunc _query

//endclass counter

?>