View Single Post
Old 05-19-2005, 07:50 AM   #11 (permalink)
DJMaze
Senior Contributor
 
DJMaze's Avatar
 
Join Date: Mar 2005
Posts: 705
DJMaze is on a distinguished road
You need a database table
Code:
CREATE TABLE hitcounter (
  ip VARCHAR(15) NOT NULL DEFAULT '',
  hits INT NOT NULL DEFAULT 1
);
PHP Code:
$db mysql_connect('localhost''username''password');
if (!
$db) {
    die(
mysql_error());
}
if (!
mysql_select_db('database_name'$db)) {
    die(
mysql_error($db));
}

$hits 0;
$ip $_SERVER['REMOTE_ADDR'];

if (!
mysql_query("UPDATE hitcounter SET hits=hits+1 WHERE ip='$ip'"$db) || mysql_affected_rows($db) < 1)) {
    
// IP isn't listed yet so add it
    
mysql_query("INSERT INTO hitcounter VALUES ('$ip', '1')"$db);
}
// IP is inserted so now get the ammount of ip's visited
$q_result mysql_query("SELECT COUNT(*) FROM hitcounter"$db);
if (
$q_result) {
    
$row mysql_fetch_row($q_result);
    
$hits $row[0];

MORE ADVANCED AND SECURE (less HD space abuse)
then change 1 php line into:
PHP Code:
$ip ip2long($_SERVER['REMOTE_ADDR']); 
And the database table
Code:
CREATE TABLE hitcounter (
  ip INT NOT NULL DEFAULT 0,
  hits INT NOT NULL DEFAULT 1,
  PRIMARY KEY (ip)
);
In the database the IP could use 7 to 15 bytes '0.0.0.0' to '255.255.255.255' but when we use ip2long() the IP will be converted to an 32bit integer which is only 4 bytes.
So on every table entry you save 3 to 11 bytes of HD space.
this doesn't look much untill there are 1 million entries.
As benefit there's also a "PRIMARY KEY" field which actualy protects the table from inserting duplicate IP's so each table entry has a unique ip.

As you see there's also a "hits" counter.
This actualy ads another feature. You can count the exact ammount of page hits instead of unique ip's.
PHP Code:
mysql_query("SELECT SUM(hits) FROM hitcounter"$db); 
This counts the total ammount of views you recieved.
PHP Code:
$hits $visitors 0;
$q_result mysql_query("SELECT COUNT(*) FROM hitcounter"$db);
if (
$q_result) {
    
$row mysql_fetch_row($q_result);
    
$visitors $row[0];
    
mysql_free_result($q_result);
}
$q_result mysql_query("SELECT SUM(hits) FROM hitcounter"$db);
if (
$q_result) {
    
$row mysql_fetch_row($q_result);
    
$hits $row[0];
    
mysql_free_result($q_result);
}
echo 
"We recieved $hits page views by $visitors visitors"
the output will be like
Code:
We recieved 15601215 page views by 49 visitors
DJMaze is offline   Reply With Quote