473,513 Members | 2,537 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Counter

zorgi
431 Recognized Expert Contributor
Hi everyone

I wrote small counter class. It counts number of daily visits. It remembers all ip addresses per page and counts them only once within any 24 hours per page and it works fine. Here is the code:
Expand|Select|Wrap|Line Numbers
  1. class Counter{
  2.     private static $instance;
  3.     public static $path = "Counter";
  4.     private $visits = array();
  5.     private $ip_reg = array();
  6.     private $current_date;
  7.  
  8.  
  9.     private function __constructor(){
  10.         $this -> $current_date = date("m.d.y");            
  11.     }
  12.  
  13.     public static function getFileInstance(){        
  14.         if(file_exists(self::$path)){
  15.             self::$instance = (unserialize(file_get_contents(self::$path)));
  16.         }else{
  17.             self::$instance = new Counter();
  18.         }
  19.  
  20.         return self::$instance;
  21.     }
  22.  
  23.     private function saveFileInstance(){
  24.         file_put_contents(self::$path, serialize(self::$instance));    
  25.     }
  26.  
  27.     private function addVisit(){
  28.         if(isset($this -> visits[$_SERVER['PHP_SELF']])) {
  29.             $this -> visits[$_SERVER['PHP_SELF']] += 1;
  30.         }else{
  31.             $this -> visits[$_SERVER['PHP_SELF']] = 1; 
  32.         }                        
  33.     }
  34.  
  35.     private function register_ip(){
  36.         if($this -> current_date != date("m.d.y")){
  37.             $this -> ip_reg = array();
  38.             $this -> current_date = date("m.d.y");
  39.         }
  40.  
  41.         $ip_adr = $_SERVER['REMOTE_ADDR'];
  42.  
  43.         if($this -> ip_reg[$ip_adr][$_SERVER['PHP_SELF']] != 1){
  44.             $this -> ip_reg[$ip_adr][$_SERVER['PHP_SELF']] = 1;
  45.             $this -> addVisit();
  46.             $this -> saveFileInstance();                        
  47.         }    
  48.         $this -> printCounter();    
  49.     }
  50.  
  51.     private function printCounter(){
  52.         echo $this -> visits[$_SERVER['PHP_SELF']];
  53.     }
  54.  
  55.     public function run(){
  56.         $this -> register_ip();
  57.     }
  58. }
  59.  
My question is what happens if I get 2 visits at the same time. They will get 2 identical instances of the class and obviously one visit will not be recorded. I know its not major issue but am just curious about possible solutions to this problem.

Thanx
Mar 10 '09 #1
4 1295
Dormilich
8,658 Recognized Expert Moderator Expert
@zorgi
I don't think that the 2nd visit gets dropped, because the server would rather queue the http request than dropping it. or in other words: 2 requests = 2 processor threads = running the code seperately. (despite the fact, that "same time" means exactly at the same microsecond)

note on code:
I assume you want it to be a singleton, __construct() must be empty (same goes for __clone())! otherwise you can create new instances outside the class.

the difference between "private function __construct()" and "public function __construct()" is:
Expand|Select|Wrap|Line Numbers
  1. class test extends Counter
  2. {
  3.     function __construct()
  4.     {
  5.         # works not with private declaration
  6.         parent::__construct();
  7.     }
  8. }
another way to create the singleton's instance:
Expand|Select|Wrap|Line Numbers
  1. self::$instance = new self;
and some speedup:
if you're fine with the timestamp (instead of the date), you can read it from the superglobals
Expand|Select|Wrap|Line Numbers
  1. $this->$current_date = $_SERVER["REQUEST_TIME"];
Mar 10 '09 #2
zorgi
431 Recognized Expert Contributor
@Dormilich

Hi Dormilich
Thank you for the pointers.

Yes I wanted to create singleton and am puzzled now. Are you saying that even I declared constructor as private I can still do this: new Counter();
from outside the class just because constructor is not empty?
Mar 10 '09 #3
zorgi
431 Recognized Expert Contributor
@zorgi
Oh thought about it bit more and figured it out... Thanks again :)
Mar 10 '09 #4
Dormilich
8,658 Recognized Expert Moderator Expert
@zorgi
of course, you do it all the time (line #17). that is not a call inside the class (by means of $this-> or self::). magic methods do not work like ordinary methods (compare it with magic constants).

a compilation of OOP patterns
Mar 10 '09 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
553
by: Shane | last post by:
:) I am following a tutorial for php (hudzilla.org) absolutely loving it however I am having trouble with the counter example <?php // your content here... $filename = 'counter.txt'; // our counter file $fp = fopen( $filename,"r"); // open it for READING ("r") $counter = fread($fp, filesize($filename) ); // read in value
16
10629
by: Paul Rubin | last post by:
I'd like to have a function (or other callable object) that returns 0, 1, 2, etc. on repeated calls. That is: print f() # prints 0 print f() # prints 1 print f() # prints 2 # etc. There should never be any possibility of any number getting returned twice, or getting skipped over, even if f is being called from
7
3413
by: JellyON | last post by:
Hi. Is there a way to delay a call to a page counter (ie. call to a server script from an IMG tag) for the purpose to not lock the page loading awaiting counter be displayed. Maybe a setTimeout() launching an equivalent of "document.write", but writing in a specific DIV ? Thanks in advance for your ideas. Actually, the counter is called...
0
5852
by: Earl Anderson | last post by:
KB Article Q140908 provided the following function to create an Auto Incrementing Counter: Function Next_Custom_Counter () On Error GoTo Next_Custom_Counter_Err Dim MyDB As Database Dim MyTable As Recordset Dim NextCounter As Long
7
3359
by: mistral | last post by:
I use htaccess to protect directory and granting access to download file only for the authorized users. Just want implement simple PHP file download counter for single file. I need track the number of downloads of this file on my website, IP address and date. Since I have no access to Apache log files, I need some other way, use script that...
0
1983
by: Trevor L. | last post by:
I decide to put a custom Hit Counter on my page (below). Then I won't be reliant on the standard FrontPage one which uses webbots. It is called by <b>Hit Counter: </b><!--#include file="_fpclass/hit_count.inc"--> The code it includes is below. OK, it works - sort of. If I go to Guestbook and then return via the Home button, the counter
12
2882
by: devospice | last post by:
Hi, I'm trying to create a download counter for individual files on a web site and I'm not sure how to do this. Right now I'm using Webalizer to just read the log files and see how many times the files I'm interested in were downloaded. The problem is Webalizer breaks it up by month and I want a running total. I'd also like to see the...
5
2076
by: jasonchan | last post by:
How would you set up a counter in javascript that goes from 5 to 0 This is what i have so far and it is not displaying in the div container "counter" for some reason... <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head>...
3
10119
blackstormdragon
by: blackstormdragon | last post by:
Here were our instructions: "My mother always took a little red counter to the grocery store. The counter was used to keep tally of the amount of money she would have spent so far on that visit to the store if she bought everything in the basket. The counter had a four-digit display, increment buttons for each digit, and a reset button. An...
2
2843
by: gumbercules | last post by:
I am designing a site that is regulary updated with new podcasts. I would like to be able to have a counter next to each podcast showing how many hits/listens/plays/views each particular podcast has gotten. eg: podcast001.mp3 plays: 12 I have set up a column in a mysql database for each podcast called 'counter'. I then tried to make a...
0
7270
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7178
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7565
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7543
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5704
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
4759
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3255
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
1612
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
817
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.