Implementation of Web Visit Counter by PHP

  • 2021-08-12 02:14:25
  • OfStack

Simple website visits counter implementation, as follows

First, explain the idea:

1. The user sends an access request to the server
2. The server reads the access number file, +1, and returns to the client
3. The server saves new browses
4. Repeat 123 for new user access

Solution (main algorithm):

1. Data file: counter. dat
2. Read the data file
Open the file;
If it does not exist, create it and take 0 as the initial data;
Otherwise, read out the data;
Close the file.
3. Write the accumulated data to the file counter. dat
Accumulate data;
Open the file;
Write data;
Close the file;
4. Output information to web pages;
Create the Count_Visitor folder.

In the Count_Visitor folder, create the Count_Visitor. php file and type the following code:


<html>
<head>
 <meta charset="UTF-8">
 <title> Browse counter -ljccccccccccc@163.com</title>
</head>
<body>
 <?php
  // Digital output web page counter 
  $max_len = 9;
  $CounterFile = "counter.dat";
  if(!file_exists($CounterFile)){  // If the counter file does not exist 
   $counter = 0;     
   $cf = fopen($CounterFile,"w"); // Open a file 
   fputs($cf,'0');     // Initialize counter 
   fclose($cf);     // Close a file 
  }
  else{          // Retrieves the value of the current counter 
   $cf = fopen($CounterFile,"r");
   $counter = trim(fgets($cf,$max_len));
   fclose($cf);
  }
  $counter++;         // Counter plus 1
  $cf = fopen($CounterFile,"w");    // Write new data 
  fputs($cf,$counter);
  fclose($cf);
 ?>
 <div id="dd" align="center">
  <span> Welcome !</span>
  <span> You are the first of this site 
   <?php
    echo $counter;       // Output counter 
   ?>
   A visitor! </span>
 </div>

</body>
</html>

If necessary, you can type css file decoration by yourself.

Variables contained in the code and their meanings

$max_len: Custom variable. The maximum number of digits of the counter;

$CounterFile: Custom variable. The file where the counter is stored (path and file name);

$counter: Custom variable. The value of the counter;

$cf: Custom variable. Open the handle of the count file;

Functions and meanings contained in code

file_exists ($CounterFile): Determines whether the file exists;

fopen ($CounterFile, "w"): Opens a file as a write. (Function comes with its own property, created if it does not exist)

fopen ($CounterFile, 'r'): Open the file as read-only.

fgets ($cf, $max_len): Reads the specified length of characters from the file

fputs ($cf, "0"): Write the character "0" to $cf

fclose ($cf): Close $cf open file

trim (fgets ($cf, $max_len)): Remove the spaces on both sides of the fetched string

That's all for today's notes!

Very simple php applet.


Related articles: