How to keep track on returning visitors

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to keep track on returning visitors

Post by Neo » Sat Feb 06, 2010 3:17 am

The easiest way to do this is by using cookies. But if the cookies are disabled by the browser, this won't work. A good solution is to keep track on the IP address and increment every 24-hours when a visitor browse the site. An example code to do this is given below.

Code: Select all

CREATE TABLE IF NOT EXISTS `table` (
  `ip` text NOT NULL,
  `online` text NOT NULL
  `hits` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1

Code: Select all

<?
// MySQL Connection
$connect = mysql_connect( 'localhost', 'username', 'password' ) or die(mysql_error());
mysql_select_db( 'database' );

$ip=$_SERVER['REMOTE_ADDR'];
$timestamp = time();

// checks if IP is in database

$getStats2 = mysql_query("SELECT * FROM `table` WHERE `ip`='$ip'") or die(mysql_error());
if( mysql_num_rows( $getStats2 ) == 0 )
{
      $select2 = mysql_query("INSERT INTO `table` (`ip`, `online`, `hits`) VALUES ('$ip','$timestamp','1')") or die(mysql_error());
}
else {

      // checks to see if last hit was before or after 24 hour mark.

      $diff = time() - 86400;
      $counthits = mysql_query("SELECT * FROM `table` WHERE `online` > '$diff' && ip='$ip'") or die(mysql_error());
      if (mysql_num_rows($counthits)==0){
            // unique hit
            while ($t=mysql_fetch_array($counthits)){
                  $hits=$t['hits'];
            }

            //checks if there is 5 hits yet...

            if ($hits=="5"){

                  // do message!

            }
            else {
                  $select2 = mysql_query("UPDATE `table` SET `online` = '$timestamp', `hits`=`hits`+1 WHERE `ip` = '$ip'");
            }

      }
      else {
            //not unique, does nothing...
      }
}
?>
Post Reply

Return to “PHP & MySQL”