Jump to content

How to create an online visitors counter

- - - - -

  • Please log in to reply
7 replies to this topic

#1
mesaber

mesaber

    Newbie

  • Members
  • Pip
  • 4 posts
Hello my friends, this is my first tutorial here, so I hope you enjoy it :).

In this tutorial we will be creating an online visitors counter. You should have knowledge of the following:-

PHP and using sessions
MySQL


---------------------------Let's get started---------------------------
First we need a MySQL table to store our information, I'll be using a table structured of two fields, one is the session_id and the other is the time.


CREATE TABLE online_visitors(

	session_id CHAR(100) NOT NULL DEFAULT '',

	time INT(11) NOT NULL DEFAULT '0'

);


Now, let's get to PHP and make sure to read the comments :)

Note: you may use the following code as a function or you may save it in a file and include it, it's up to you. As for me, I will save it in a separate file :).

Firstly, I will store my database connection information in a separate file and include it in my counter file. The database connection file is called dbc.php and in contains the following code:-

dbc.php

<?php

	//connect to the database

	$dbc = mysql_connect("localhost","root","") or die("Couldn't connect to the database server<br />".mysql_error());

	

	//select the database 'test'

	$dbs = mysql_select_db("test") or die("Couldn't select to the database<br />".mysql_error());

?>


counter.php

<?php

	require("dbc.php");	//Require the database connection

	

	//First we have to start the session only if it has not been started

	if(!isset($_SESSION)){

		session_start();

	}

	

	

	$session_id = session_id();	//We assign the session id to the variable $session_id

	

	$time = time(); 	//We assign the current time to the variable $time

	

	$time_limit = $time-600;	//We give the session only 10 minutes if it exists

	

	/**

	*We need to check the session_id is already stored or not

	*/

	$num = mysql_num_rows(mysql_query("SELECT * FROM online_visitors WHERE session_id='{$session_id}' LIMIT 1"));

	

	//if it doesn't exist, then we'll store it

	//And if does exist, we will update the session's time in the DB

	if($num != 1){

		$sql = "INSERT INTO online_visitors VALUES('{$session_id}','{$time}')";

		$query = mysql_query($sql) or die("Error<br />".mysql_error());

	}else{

		$sql = "UPDATE online_visitors SET time='{$time}' WHERE session_id='{$session_id}'";

		$query = mysql_query($sql) or die("Error<br />".mysql_error());

	}

	

	//Now the following code is to get the count of visitors currently online

	$noov = mysql_num_rows(mysql_query("SELECT * FROM online_visitors"));  //noov = number of online visitors

	

	echo 'Visitors currently online: ',$noov;

	

	//Now, check if the session was stored for more than 10 minutes and delete it if it is.

	$delete_session = mysql_query("DELETE FROM online_visitors WHERE time<'{$time_limit}'");

	

	//close the connection

	mysql_close();

?>


Now, let's get to the explanation:-

1: We required the dbc.php which contains the database connection information

2: We are checking if the session has been already started, if it's not, then start the session

3: We assign the session id to the variable $session_id

4: We created two variables, one is the current time and the other contains the current time minus 10 minutes

5: We need to check the session_id is already stored or not, so we query the database and see if it doesn't exist, then we'll store it and if it does exist, we will update the session's time in the DB

6:We get the count of the total session in the table and print it.

7: We then check if the session has been in the database for more than 10 minutes, if it is, then we will delete it.

This is it, I hope you enjoyed this easy tutorial.

See ya ;)

Edited by mesaber, 18 July 2011 - 01:20 AM.
Adding more information


#2
bbqroast

bbqroast

    Codecall Addict

  • Members
  • PipPipPipPipPipPipPip
  • 554 posts
  • Location:/etc/passwd
Nice but,
I like it when you explain the code bits by bit!
Please, write clearly with proper structure. Double spacing makes the text feel un-jointed, Capitalizing Every Word Means People Stop Before Every Word Sub-Consciously Which Is A Pain In The Backside, and use code tags! (The right most styling box).

#3
mesaber

mesaber

    Newbie

  • Members
  • Pip
  • 4 posts
Thanks for reply bbqroast :).

I am sure I explained the code in the comments my friend.

#4
bbqroast

bbqroast

    Codecall Addict

  • Members
  • PipPipPipPipPipPipPip
  • 554 posts
  • Location:/etc/passwd
Yeah I know, I'm sorry but it kind of feels like you just found this in your website and put it up, commenting on the bits- I guess mainly because of the unexplained DBC file.
You should explain the contents of the dbc file for beginners (many might think you mean MSSQL).
Please, write clearly with proper structure. Double spacing makes the text feel un-jointed, Capitalizing Every Word Means People Stop Before Every Word Sub-Consciously Which Is A Pain In The Backside, and use code tags! (The right most styling box).

#5
mesaber

mesaber

    Newbie

  • Members
  • Pip
  • 4 posts
Ok my friend, I will explain it.

In case you haven't noticed, I said I'll be using MySQL :).

Any way, I'll do it right now, cheers .

#6
Upstream

Upstream

    Learning Programmer

  • Members
  • PipPipPip
  • 44 posts
Thanks for your tutorial.

I was wondering if this does not create a lot of overhead? You could handle the update at the client side by storing this info in the session var itself. No need to access the db at every page load I would think. Ultimately you could also count the number of active sessions on the server and return this.
"The question of whether a computer can think is no more interesting than the question of whether a submarine can swim." (Edsger Dijkstra)

#7
mesaber

mesaber

    Newbie

  • Members
  • Pip
  • 4 posts
Thanks for reply Upstream.

Nice one, and maybe it will be faster :).

But as you know that every programmers has his own way of solving the problem. It doesn't matter what way I choose to solve the problem. What matters to me is the problem to be solved.

Thanks again.

#8
bbqroast

bbqroast

    Codecall Addict

  • Members
  • PipPipPipPipPipPipPip
  • 554 posts
  • Location:/etc/passwd
Good point, I would also store the IP address. That way you can load all the results into a array use PHPs vast amount of array functions to filter out the same IPs before counting the amount of entries in the array- you will end up with the amount of unique visitors and the amount of page hits.

You could also graph the way visitors move through the site (providing you record the current page) allowing you to create things such as recommended boxes (things that other users went to after that page).

Not to mention it could become handy in the event of a intrusion (especially if it worked on the admin pages).

How could you count the amount of active sessions?? I guess its possible I just wonder how...
Please, write clearly with proper structure. Double spacing makes the text feel un-jointed, Capitalizing Every Word Means People Stop Before Every Word Sub-Consciously Which Is A Pain In The Backside, and use code tags! (The right most styling box).




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users