Php counter with cookies

19.10.2007, 1:22
Submited in: Php | Total Views: 39690

Big thing when you are creating counter for your web sites is to disable counting same visitors every time he/she visit your page. To avoid this you would use cookies in this case because you want do disable counting for day not session.

What we need to do now is to create new table in our existing database or new using below sql query:

CREATE TABLE 'stats' (
'counter' INT NOT NULL

INSERT INTO 'stats' ( 'id' , 'counter' ) VALUES (NULL , '0');

After you have created new table needed for this counter we need to create new file for example: "counter.php".

Copy & Paste code below to newly created file:


// connect to mysql
$link = mysql_connect('localhost', 'write_here_mysql_username', ' write_here_mysql_password');

// select database

// cookie details here
$counted = $HTTP_COOKIE_VARS["counter"];

// if this is first visitor then

// we create cookie for visitor

// add counter to database
    mysql_query("UPDATE stats SET counter=counter+1");

$query=mysql_query("SELECT * FROM stats");

while($row=mysql_fetch_assoc($query)) {
$stats=$row['counter']; }


Normally now you want to show this stats somewhere... What you need to do if you want to track every visit?

Make sure you make this:
1.  include this file in page you want to track

<?php include("counter.php"); ?>

2. Print counter in part of page you want to show number of visits

<?php print $stats; ?>

That's all.

Are you a website owner?
Click here to register and submit your tutorials!

Browse by category

Most popular tutorials