You can often see labels like : ‘Post/Page visited : X times’ at blogs and various websites. Webmasters usually like to know how many times has been a particular post/website loaded, viewed by site visitors. PHP offers good basis for solving such a ‘problem’. There are many good scripts on the net that use an external TXT file to read and write to some specific data regarding page loads.
The problem however is tracking guests and members which have not logged in to your site. You can not track a user by his IP because some users do not have fixed IP. To set a cookie to the user browser to see if this is the same returning user is a good idea and a script with cookies will definatelly solve this issue the most elegant way.
My solution is a small PHP script that will track and insert visitors (registered members AND guests) into a database with NO needs of cookies, nor an external txt (or other) file.
If you know PHP/MySql, but you don’t want to (or you cannot) work with COOKIES, this script may help you out to track the page loads and visitors of your site.
Here’s the code listing :
// PHP SCRIPT FOR DISPLAYING NUMBER OF UNIQUE VISITS OF A PARTICULAR PHP PAGE WITHOUT COOKIES
// Written by : Victor Dujmovic – copyright – 03/09/2009
// http://www.blogofd.com
// dujmovicv@gmail.com
// skype : dujmovicv
// msn : blogofd@hotmail.com
$query_loads = “SELECT * from visited_stuff WHERE username = ‘$session->username’ AND stuff_id = ‘$this_id’
ORDER by id ASC”;
$result_loads = mysql_query($query_loads) or die(‘Error : ‘ . mysql_error());
$num_loads = mysql_num_rows($result_loads);
$username = $session->username;
$today = date(‘Ymd’);
$this_day = (int)$today;
if ($num_loads == 0 and $this_id != 0)
{
$query_update = “INSERT INTO visited_stuff SET
stuff_id = ‘$this_id’,
username = ‘$username’,
visited = ‘$today’,
nr_visits = 1 “;
mysql_query($query_update) or die(‘Error, query failed. ‘ . mysql_error());
}
// GET NUMBER OF PAGELOADS
$query_nr_loads = “SELECT * from visited_stuff WHERE username = ‘$session->username’ AND stuff_id = ‘$this_id’
ORDER by id ASC”;
$result_nr_loads = mysql_query($query_nr_loads) or die(‘Error : ‘ . mysql_error());
while($row_nr_loads = mysql_fetch_array($result_nr_loads))
{
$that_day = (int)$row_nr_loads['visited'];
$nr_visits = $row_nr_loads['nr_visits'];
if ($this_day != $that_day)
{
$new_nr_visits = $nr_visits + 1;
$query_loads = “UPDATE visited_stuff SET
visited = ‘$today’,
nr_visits = ‘$new_nr_visits’
WHERE username = ‘$session->username’ AND stuff_id = ‘$this_id’ “;
mysql_query($query_loads) or die(‘Error, query failed. ‘ . mysql_error());
}
if ($this_day == $that_day and $session->username == “guest”)
{
$new_nr_visits = $nr_visits + 1;
$query_loads = “UPDATE visited_stuff SET
visited = ‘$today’,
nr_visits = ‘$new_nr_visits’
WHERE username = ‘$session->username’ AND stuff_id = ‘$this_id’ “;
mysql_query($query_loads) or die(‘Error, query failed. ‘ . mysql_error());
}
}
// END NUMBER OF PAGELOADS