PHP & MySQL Visitors Counter Tutorial
Ranked #1,257 in Internet, #70,847 overall
Creating a Visitors Counter script
- counter.php
This file will contain the script for the functions of the counter:
- initCounter( )
initializes the counter by making a log of the current visitor and updating the counter in the database. - getCounter($mode)
returns the counter in $mode ( unique visitors or all hits ).
- initCounter( )
The Database
Setting up the MySQL Database for the script.
id
location
ip
which is in SQL code:
CREATE TABLE IF NOT EXISTS `counter` (
`id` int(250) NOT NULL AUTO_INCREMENT,
`location` varchar(250) NOT NULL,
`ip` varchar(250) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The script
Creating the php script.
mysql_connect("localhost", "root", "password");// server, user, pass
mysql_select_db("webcodez"); // database
We'll start with creating the first function of the script: initCounter. This function needs to make a log of the visit inside of the database table. It needs the ip of the visitor and the location of the file to do this. To acquire these informations we can use the global array $_SERVER, which contains all kinds of useful data ( including the visitor's ip and server file path ).
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR']; //get visitor ip
$location = $_SERVER['PHP_SELF']; //get server file path
//create log in database table 'counter'
}
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR']; //get visitor ip
$location = $_SERVER['PHP_SELF']; //get server file path
//create log in database table 'counter'
$create_log = mysql_query("INSERT INTO counter(ip,location)VALUES('$ip', '$location') ");
}
function getCounter($mode) {
if($mode == "unique") {
$get_res = mysql_query("SELECT DISTINCT ip FROM counter WHERE location = '".$_SERVER['PHP_SELF']."' ");
}else{
$get_res = mysql_query("SELECT ip FROM counter WHERE location = '".$_SERVER['PHP_SELF']."' ");
}
}
function getCounter($mode) {
if($mode == "unique") {
$get_res = mysql_query("SELECT DISTINCT ip FROM counter WHERE location = '".$_SERVER['PHP_SELF']."' ");
}else{
$get_res = mysql_query("SELECT ip FROM counter WHERE location = '".$_SERVER['PHP_SELF']."' ");
}
$res = mysql_num_rows($get_res);
return $res;
}
function getCounter($mode, $location = NULL)
we give it as default value NULL and give it the value of the the location of the current page if no other value is given. This way, when calling the function, it's not necessary to provide the location of the page but it IS possible. What we do need to do now, is replacing $_SERVER['PHP_SELF'] by $location inside of the function script. This way it will use the newly created argument $location, so that the user of this function can also provide a different location rather than the current page.function getCounter($mode, $location = NULL) {
if(is_null($location)) {
$location = $_SERVER['PHP_SELF'];
}
if($mode == "unique") {
$get_res = mysql_query("SELECT DISTINCT ip FROM counter WHERE location = '$location' ");
}else{
$get_res = mysql_query("SELECT ip FROM counter WHERE location = '$location' ");
}
$res = mysql_num_rows($get_res);
return $res;
}
counter.php
<?php
function initCounter() {
$ip = $_SERVER['REMOTE_ADDR']; //get visitor ip
$location = $_SERVER['PHP_SELF']; //get server file path
//create log in database table 'counter'
$create_log = mysql_query("INSERT INTO counter(ip,location)VALUES('$ip', '$location') ");
}
function getCounter($mode, $location = NULL) {
if(is_null($location)) {
$location = $_SERVER['PHP_SELF'];
}
if($mode == "unique") {
$get_res = mysql_query("SELECT DISTINCT ip FROM counter WHERE location = '$location' ");
}else{
$get_res = mysql_query("SELECT ip FROM counter WHERE location = '$location' ");
}
$res = mysql_num_rows($get_res);
return $res;
}
?>
Update: Instead of using mysql_num_rows to count the amount of results, we could also do this within the query (=faster):
function getCounter($mode, $location = NULL) {
if(is_null($location)) {
$location = $_SERVER['PHP_SELF'];
}
if($mode == "unique") {
$get_res = mysql_query("SELECT COUNT(DISTINCT ip) AS amt FROM counter WHERE location = '$location' ");
}else{
$get_res = mysql_query("SELECT COUNT(ip) AS amt FROM counter WHERE location = '$location' ");
}
$res = mysql_fetch_assoc($get_res);
return $res['amt'];
}
Usage
The usage of our visitor counter script.
<?php
//usage of the script in an example webpage
include_once("counter.php"); //do include the actual visitor counter script
initCounter(); //make a log of the current visit
echo "Hi there, this is an example web page. <p>";
echo "This webpage has got a total of ".getCounter('hits')." hits from which ".getCounter('unique')." unique.";
?>
You might also like ...
Comments & Questions
What kind of PHP tutorial would you like to see next?
-
-
dave
Aug 5, 2011 @ 12:34 pm | delete
- There are some things, I don't get. First the SQL-code. You advise to create a table with three columns. every column-value gets a length of maximum 250 chars. does it makes sense for the integer value of `id`? why aren't you using 'int' without any length? again in 'location' and 'ip'. do you really think there are ip adresses with a length of 250 chars? the same about 'location': are you and the most readers of your tutorial creating such deep directory trees?
O.K., thats enough. Maybe there is a little mistake.
The next thing, I was asking me, and thats why I'm looking for some examples, what is about visitors with a static ip adress? Or what about the users that are visiting the site more times a day, it doesn't count hits or is resetting the ip adress after a while. Maybe you can follow my thoughts.
-
-
-
webcodez
Aug 5, 2011 @ 2:44 pm | delete
- Hi there dave,
First of all: Thank you for your feedback.
As for the SQL code: the 250 chars for id and location are done out of ease from my side ( I'm sorry I can be lazy too, sometimes :P ) but also to not overcomplicate things for a simple visitor counter. You're right about the IP address size: I thought I already edited/fixed the article for that part but apperantly I did not, so I will do so asap.
As for the multiple hits from one visitor: that's why in the tutorial we create the function that can get all unique hits ( counting all hits of one IP as ONE (no double counts for same IP/person's hits) ) and all total hits ( counting all hits from 1 visitor as multiple ). If you meant to do this for each specific day, we could alter the query adding the following statement: WHERE timestamp > time()-86400
I hope this helps!
Best Regards,
Webcodez.
-
-
-
Hein.
Mar 15, 2012 @ 12:13 pm | delete
- Hi is it possible for you to explain how i could achieve the operation mentioned above?
{# to do this for each specific day, we could alter the query adding the following statement: WHERE timestamp > time()-86400 #} ?
I am fairly new to all of this so unfortunately i need a lot of guidance. =(
-
-
-
don2fuentes
Jun 24, 2011 @ 11:50 pm | delete
- very nice. You could also make it reusable by using the object oriented approach
-
-
-
webcodez
Jun 25, 2011 @ 4:42 am | delete
- Thanks, that's actually a pretty good idea. I might as well post that approach, perhaps in a new tutorial or within this one.
-
Related Products (Amazon)
Related Products(eBay)
by webcodez
"Give a man a program and you'll frustrate him for one day. Teach a man to program and you'll frustrate him for a whole lifetime."
webcodez
GameHeroes
more »
- 21 featured lenses
- Winner of 14 trophies!
- Top lens » PHP & MySQL Poll System Tutorial
Explore related pages
- PHP & MySQL Poll System Tutorial PHP & MySQL Poll System Tutorial
- PHP & MySQL Login System Tutorial PHP & MySQL Login System Tutorial
- PHP basics tutorial PHP basics tutorial
- PHP Banner Rotator Tutorial PHP Banner Rotator Tutorial
- PHP Email Validation Tutorial PHP Email Validation Tutorial
- PHP Sessions and Cookies Tutorial PHP Sessions and Cookies Tutorial