A function that will provide counting for an unlimited amount of pages. Checks IPs and won't up count if the same IP hits the same page over and over.
By : Matt
<? function Counter($page = '') { /* this function will take $page as an arguement. * using different values for $page will allow * you to use a different counter on each page. * if you want the same counter for all of your * site then don't pass in $page */
/* connect to and select database */ mysql_connect ('localhost','username','password'); mysql_select_db ('database');
/* set expire time for ips * 600 seconds = 10 minutes */ $expire = time() - 600; /* delete from table where ip has expired */ $query = "DELETE FROM counter_ips " . "WHERE viewtime < $expire " . "AND page = '$page'"; mysql_query ($query);
/* now we check to see if the users * ip exists in the table */ $query = "SELECT ip FROM counter_ips " . "WHERE ip = '{$_SERVER['REMOTE_ADDR']}'" . "AND page = '$page'"; $result = mysql_query ($query); if (mysql_num_rows ($result) > 0) { /* if the ip existed, update the view time */ $viewtime = time(); $query = "UPDATE counter_ips SET viewtime = '$viewtime'" . "WHERE ip = '{$_SERVER['REMOTE_ADDR']}'" . "AND page = '$page'"; mysql_query ($query); } else { /* ok time to record a hit and the ip */
/* first check if a record exists for $page */ $query = "SELECT num FROM counter " . "WHERE page = '$page'"; $result = mysql_query ($query); if (mysql_num_rows ($result) == 0) { /* if no row, add one */ $query = "INSERT INTO counter VALUES " . "(1,'$page')"; mysql_query ($query); } else { /* there is a row so just update it */ $query = "UPDATE counter SET num = num + 1 " . "WHERE page = '$page'"; mysql_query ($query); } /* add ip to ip table */ $viewtime = time(); $query = "INSERT INTO counter_ips VALUES " . "('{$_SERVER['REMOTE_ADDR']}', '$page', $viewtime)"; mysql_query ($query); }
/* now we get the counter value and return it */ $query = "SELECT num FROM counter WHERE page = '$page'"; $row = mysql_fetch_assoc (mysql_query ($query));
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.