How To Create A PHP Based Hit Counter - With MySQL

free web hosting
Free Web Hosting > Computers & Tech > How-To's and Tutorials > Programming > PHP

How To Create A PHP Based Hit Counter - With MySQL

Cloak
websaint recently posted a PHP hit counter using a flat-file to store information.

This is a guide a wrote a little while ago - it was for another web site, but I'll post it here as well.

-----------------------------------------------------------------------------------

First and foremost, you need to create a new table. You can use a whole new database if you want (and assuming you have one free), but it's a bit of a waste.

For this guide, our table will be called 'hits', and will contain two fields - 'unique' and 'total'. The first field, 'unique', will log all unique visits/hits to the site. And 'total' will log all visits to the site, unique or not. You can do this from within PHP:
CODE
mysql_query("CREATE TABLE hits (unique int(6), total int(7))");

Or just go directly through MySQL:
CODE
CREATE TABLE hits (unique int(6), total int(7));

Now obviously, you can change the buffer size around if you want, depending on how active you are expecting your site to be. In this example, the field 'unique' can contain any number up to 6 digits long - that is to say, any number from 0 to 100,000, and 'total' can store up to 7 digits in one entry. The average person that is reading this and is interested in creating a counter from it is not going to be having astronomical numbers of hits to their site, so what I've used is probobly a bit of overkill.

After you've created a table, you need to construct a script that will log data to the table.

Because we are wanting to log unique hits, hte use of cookies is required. This obviously doesn't work for all users, but letting a few slip through the nets shouldn't really damage things.

CODE
<?php
// Assumes: you are already connected to MySQL,
// and have selected the database you will be using;
// That the visitor is cookie-compatible;
// That the visitor has not cleared their cookies.


// Also note that this script is very optimizable.
// It is intended only to work and to be easy to understand,
// not to win any awards.

$result = mysql_query("SELECT * FROM hits");
$data = mysql_fetch_assoc($result);
$total_hits = $data['total'];
$unique_hits = $data['unique'];
// Firstly, grab the existing data from MySQL


$total_hits++;
mysql_query("UPDATE hits SET total = '" . $total_hits . "'");
// The total number of hits is going to be incremented
// regardless of the situation, so this can be done first
// to get it out of the way


if(isset($_COOKIE['visited'])) {
  $cookie = $_COOKIE['visited'];
  // Our global variable index will be called 'visited',
  // to make it easy to remember
} else {
  $cookie = false;
}

if(!$cookie) {
  $unique_hits++;
  mysql_query("UPDATE hits SET unique = '" . $unique_hits . "'");
  // The value of $cookie is NOT true, meaning that the user
  // has not yet been counted
} else {
  setcookie("visited","1",time()+86400,"/");
  // Now, we set the cookie's value. Here, it is set to
  // expire in 86,400 seconds (24 hours) - you can
  // change this is if you like, but it ensures that the
  // same person won't be counted as a unique visitor
  // more than once in a 24-hour period
}

mysql_free_result($result);
mysql_close();

?>


And there we have it - a fully functional hit-counting script. Now all you would need to do is save the file somewhere, and use:
CODE
<?php include("script-path.php"); ?>


Now, what if you want to retrieve the number of hits your site has received, so you can display it somewhere?

This is very easy to achieve. Here are a couple of custom-coded functions that'll do it for you:

CODE


// Assumes: You are connected to MySQL
// and have selected the database
// (eg. mysql_connect(), mysql_select_db())

function UniqueHits() {
  $result = mysql_query("SELECT unique FROM hits");
  $data = mysql_fetch_assoc($result);
  $unique_hits = $data['unique'];
  mysql_free_result($result);
  return $unique_hits;
}

function TotalHits() {
  $result = mysql_query("SELECT total FROM hits");
  $data = mysql_fetch_assoc($result);
  $total_hits = $data['total'];
  mysql_free_result($result);
  return $total;
}


Now, you could put that in a second script, and include a reference to it as well - but it would just be much easier all around to add it to the end of the other script (before the ?>).

Now all you have to do is:
CODE
echo UniqueHits();
// OR
echo TotalHits();

In order to use them.

-----------------------------------------------------------------------------------

Review:
Our MySQL table was named 'hits', and was created with:
CREATE TABLE hits (unique int(6), total int(7));

The final script was, including everything, was:
CODE
<?php
// Assumes: you are already connected to MySQL,
// and have selected the database you will be using;
// That the visitor is cookie-compatible;
// That the visitor has not cleared their cookies.


// Also note that this script is very optimizable.
// It is intended only to work and to be easy to understand,
// not to win any awards.

$result = mysql_query("SELECT * FROM hits");
$data = mysql_fetch_assoc($result);
$total_hits = $data['total'];
$unique_hits = $data['unique'];
// Firstly, grab the existing data from MySQL


$total_hits++;
mysql_query("UPDATE hits SET total = '" . $total_hits . "'");
// The total number of hits is going to be incremented
// regardless of the situation, so this can be done first
// to get it out of the way


if(isset($_COOKIE['visited'])) {
  $cookie = $_COOKIE['visited'];
  // Our global variable index will be called 'visited',
  // to make it easy to remember
} else {
  $cookie = false;
}

if(!$cookie) {
  $unique_hits++;
  mysql_query("UPDATE hits SET unique = '" . $unique_hits . "'");
  // The value of $cookie is NOT true, meaning that the user
  // has not yet been counted
} else {
  setcookie("visited","1",time()+86400,"/");
  // Now, we set the cookie's value. Here, it is set to
  // expire in 86,400 seconds (24 hours) - you can
  // change this is if you like, but it ensures that the
  // same person won't be counted as a unique visitor
  // more than once in a 24-hour period
}

mysql_free_result($result);

function UniqueHits() {
  $result = mysql_query("SELECT unique FROM hits");
  $data = mysql_fetch_assoc($result);
  $unique_hits = $data['unique'];
  mysql_free_result($result);
  return $unique_hits;
}

function TotalHits() {
  $result = mysql_query("SELECT total FROM hits");
  $data = mysql_fetch_assoc($result);
  $total_hits = $data['total'];
  mysql_free_result($result);
  return $total;
}

mysql_close();

// Script originally created by Cloak / Astahost.com

?>


And there we have it. A fully functional, ready-to-go, PHP hit-counting script that not only logs page views, but also unique visits to your site.

Notes:
-- All coding is done by me. As such, it is done in my own style, meaning that you might not like it.
-- This script was written 'on-the-fly' while I was writing this quick guide, and it hasn't yet been tested at all. It might contain a bug or syntax error or two.
-- You are free to use and modify this script AS YOU WISH, as long as it includes the final comment:
// Script originally created by Cloak / Astahost.com
Note that as this is a commented line (//), it will not be visible by anyone who uses this script from your site.

Hope you found this helpful/useful/maybe even educational.

 

 

 


Reply

vmkrightpoint
Nice Script! lol

Reply

rockarolla
only to mention, I think the word unique
QUOTE
CODE
mysql_query("CREATE TABLE hits (unique int(6), total int(7))");


is not allowed...

I would prefer to make the counter using session...just in case cookies aren't allowed and because using cookies is not always safe. I think they do encourage ppl to use session for cookies.

Reply


Got an Opinion! Express your Views! (no registration):-
Add your Reply/ Opinion/ Views/ Comments/ Suggestion/ Questions/ Queries etc.
Posts with decent grammar & English will be accepted and please refrain from profanities.
For asking a Question, We recommend you to sign-up (for free) so that you can track the topic easily.

Nature of your Post*: Opinion/ Reply/ Comments
Question/Query
Feedback to us.
       
Name   Email
Title/Question*

(Maximum characters: 10,000)
You have characters left.

Recent Queries:-
  1. php create gif counter source - 105.02 hr back. (1)
  2. unique php page counter - 125.60 hr back. (1)
Similar Topics

Keywords : php, hit, counter, mysql

  1. How To: Display A Members/user List.
    With PHP, Mysql, and HTML. (3)
  2. Js/php/mysql Timer
    (2)
    In this tutorial I show a JS/PHP Timer. I use ingame password resetting as an example. I did borrow
    the JS from another online tutorial but the rest I did on my own. It works as its the source from my
    pass reset mostly. CODE <?php if ($action == 'action1') // this is the
    action being performed, example: index2.php?page=passreset { // Process ID would go here. It has
    the user's id, and other things depending on the process. However because this is used to fetch
    the process from the DB it cannot have things like time or date as thy cha....
  3. Creating A Content Managing System
    Using MySQL (15)
    This tutorial is for beginners that know some php and know the basics of MySQL. I will tell you how
    to make a simple Content Managing System. A Content Managing System is a way of editing and adding
    your content using your browser, so you dont have to go trough ftp all the time. This CMS uses
    MySQL databases. So what we need to do is to create a database. Well go through this step by step to
    make it as easy as posible: 1. Go in to your cPanel and select phpMyAdmin. 2. Write the name of
    your database in the input box under the text: Create new database. This database ....
  4. Make Your Own Very Simple Counter Using PHP!
    (35)
    Hi!! I'm going to show you how to make your own counter useing php!!
    /tongue.gif' border='0' style='vertical-align:middle' alt='tongue.gif' /> It's really easy and
    you woun't have to keep seaching the net for free and bannerless counters. So here comes the
    script: CODE <?php //Simple class for counting visits //Written by WebSaint class
    Teller {    function count() {    $countfile = file("alle.txt");
       $count = $countfile[0];    $count= $count + 1;    $f....

    1. Looking for php, hit, counter, mysql

*RANDOM STUFF*





*SIMILAR VIDEOS*
Searching Video's for php, hit, counter, mysql
advertisement




How To Create A PHP Based Hit Counter - With MySQL



 

 

 

 

ADD REPLY / Got an Opinion! a humble request :-) RAPID SEARCH! Free Hosting [X]
Express your Opinions, Thoughts or Contribute your information that might help someone here.
Ask your Doubts & Queries to get answers.. "Together, We enlight each other!"
Register FREE for AD-FREE forum, Create your own topics, Ask Questions, track topics, setup subscriptions & notifications and Get a Free Website w/ Email and FTP.
500MB Space *No Ads*, CPanel, FTP, PHP, MySQL, EMails - 100% FREE