Tracking unique visitors only?

Kyle picture Kyle · Oct 23, 2010 · Viewed 27.4k times · Source

Currently I have a file called "hits.php" and on any page I want to track page hits I just use <?php include("hits.php"); ?>

How can I track unique visitors only though? My hits are false since it can be refreshed by the same person and hits go up.

Here's my source:

<?php
 $hits = file_get_contents("./client/hits.txt"); 
 $hits = $hits + 1; 

 $handle = fopen("./client/hits.txt", "w"); 
 fwrite($handle, $hits); 
 fclose($handle); 

 print $hits; 

?>

I don't really know how I could do cookie checking... is there a way to check IP's? Or what can I do?

Thanks StackO.

Answer

user372743 picture user372743 · Oct 23, 2010

The simplest method would be cookie checking.

A better way would be to create an SQL database and assign the IP address as the primary key. Then whenever a user visits, you would insert that IP into the database.

  1. Create a function included on all pages that checks for $_SESSION['logged'] which you can assign whatever 'flag' you want.
  2. If $_SESSION['logged'] returns 'false' then insert their IP address into the MySQL database.
  3. Set $_SESSION['logged'] to 'true' so you don't waste resources logging the IP multiple times.

Note: When creating the MySQL table, assign the IP address' field as the key.

<?php 
  session_start();
  if (!$_SESSION['status']) {
    $connection = mysql_connect("localhost", "user", "password");
    mysql_select_db("ip_log", $connection);

    $ip = $_SERVER['REMOTE_ADDR'];
    mysql_query("INSERT INTO `database`.`table` (IP) VALUES ('$ip')");

    mysql_close($connection);
    $_SESSION['status'] = true;
  }
?>