Image Hit counter php mysql
Image Hit counter php mysql
Image Hit counter php mysql
This is a simple but advanced graphical hit counter using php and mysql. The main advantage of this script is you can change the counter style dynamically. The only restriction here is to have 0 to 9 numeric image files with naming convention as 0.jpg, 1.jpg, 2.jpg etc., till 9.jpg. Each style can be on different directories.
The counter here works with the help of cookies which are set to expire after 1 day. We can even make it much more stable by saving the IP Address of the user in the database which i will write as a separate tutorial later.
The first step is the create a Mysql database with a table inside that.
CREATE DATABASE `counter` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci; USE `counter`; CREATE TABLE IF NOT EXISTS `counter_data` ( `counter` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The second step is to create a file, counter.php and add the below code. Modify the Mysql values accordingly.
<?php #Create cookie with 1 day expiry $expire=time()+86400; $dir_name=$_GET['counterdir']; #Connect to database mysql_connect("localhost", "root", "root123") or die(mysql_error()); mysql_select_db("counter") or die(mysql_error()); $result = mysql_query("SELECT * FROM counter_data"); $row = mysql_fetch_array($result); $value = $row['counter']; #Check whether the cookie has been set if (!isset($_COOKIE["hit"])) { $add = $value+1; $update = mysql_query("update counter_data set counter=$add"); echo "You are visitor number $add!!!<br>"; $display = $add; setcookie("hit", "counter", $expire); } else { echo "You have already visited this webpage. Counter still $value!!<br>"; $display = $value; } $a=str_split($display); $count = count($a); $i=0; for($i==0;$i<$count;$i++) { switch($a[$i]){ case "0": echo "<img src=$dir_name/0.jpg>"; break; case "1": echo "<img src=$dir_name/1.jpg>"; break; case "2": echo "<img src=$dir_name/2.jpg>"; break; case "3": echo "<img src=$dir_name/3.jpg>"; break; case "4": echo "<img src=$dir_name/4.jpg>"; break; case "5": echo "<img src=$dir_name/5.jpg>"; break; case "6": echo "<img src=$dir_name/6.jpg>"; break; case "7": echo "<img src=$dir_name/7.jpg>"; break; case "8": echo "<img src=$dir_name/8.jpg>"; break; case "9": echo "<img src=$dir_name/9.jpg>"; break; default: echo "None"; } } ?>
How to call the above script?
It is very simple. If you have a website with name somewebsite.com, assuming that the counter style folders named style1, style2 etc., are in the root directory then all you have to do is include the URL with the query string http://somewebsite.com/counter.php?counterdir=style1 or http://somewebsite.com/counter.php?counterdir=style2 likewise according to the style you prefer.
To include this page in any PHP script
<?php include('counter.php?counterdir=style1'); ?>
Download number images from http://www.webnots.com/free-number-images.html
Image Hit counter php mysql,