菜单

PHP realize website access counter

2017年11月22日 - PHPer

Simple website access counter implementation, as follows

First of all, explain the ideas:

1. users send requests to the server

2. the server reads the access number file, +1, and returns to the client

3. server saves new browsing times

4. new users access, repeat 123 can

Solutions (main algorithms):

1. data file: counter.dat

2. read out the data file

Open file;

If it does not exist, create, and 0 for the first data;

Or read data;

Close file.

3. write the accumulated data to the file counter.dat

Accumulated data;

Open file;

Writing data;

Close file;

4. output information to web pages;

Create 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 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 file

Fputs ($cf,’0′); / / initialize the counter

Fclose ($cf); / / close the file

}

Else{/ / retrieve the current counter value

$cf = fopen ($CounterFile, “R”);

$counter = trim (fgets ($cf, $max_len));

Fclose ($cf);

}

$counter++; / / add a counter

$cf = fopen ($CounterFile, w); / / write new data

Fputs ($cf, $counter);

Fclose ($cf);

&gt?;

< div id= “DD” align= “center” >

< span> welcome! < /span>

< span> you are the first station

<? PHP

Echo $counter; / / output counter

&gt?;

Bit visitor! < /span>

< /div>

< /body>

< /html>

If you need, you can type your own CSS file for decoration

The variables contained in the code and their meanings

$max_len: Custom variables. Maximum digit of counter;

$CounterFile: Custom variables. Files stored in counters (paths and filenames);

$counter: Custom variables. Counter value;

$cf: Custom variables. Open the handle to count file;

Functions and meanings contained in code

File_exists ($CounterFile): determine whether the file exists;

Fopen ($CounterFile, “W”): open the file in writing mode. (function comes with attributes, if not exists)

Fopen ($CounterFile,’r’): open a file in read-only mode.

Fgets ($cf, $max_len): read the specified length of characters from a file

Fputs ($cf, “0”): write the character “0” to $cf

Fclose ($cf): close the $cf open file

Trim (fgets ($cf, $max_len)): removes the whitespace on both sides of the string

That’s all for today’s notes!

Very simple PHP small application.

发表评论

电子邮件地址不会被公开。