PHP Tutorials. Application Example 8

Source: Internet
Author: User
Tags define count empty header strlen mysql database advantage
Tutorial | Application instance PHP customize your own register
The counter is the most direct way for a web visitor to know the popularity index of the page or site, and the number of visitors is also the best basis for advertising advertisers. Although many sites provide free counters, but after all, not their own hand-made, can not reflect their own characteristics. The following is a detailed discussion of the production process of the Register in PHP environment.

The flow of the visitor counter is as follows:

The first user browses to a page.

The server program reads the number of times the page has been browsed from the database or archive.

Add the number of times to a store and send it back to the first user.

The next user browses to a page.

The server program reads the number of times the page has been browsed from the database or archive.

Add the number of times to the storage and send it back to the next user.

There is no direct counter function in PHP, but with its powerful features, we can easily write a counter ourselves. The implementation of the counter is divided into two stages: one is the implementation of the count, and the other is the realization of the digital display. In the implementation of the count, there are two ways: one is based on the number of files, and the other is based on the database counting method. Also in the implementation of the display of numbers there are two ways: one is the normal text display, and the second is the graphical display. These four kinds of situations are introduced separately below.

One, the realization of the Count

1. File-based Count

Principle: Record the number of visitors in a text file, when the page is accessed, open the file and read out the previous number of visitors, plus 1, get the latest number of visitors, and then the latest access figures back to the record number of visitors to the file.
Achieve

<?php

$counterFile = "Counter.txt";
if (!file_exists ($counterFile)) {
To determine whether a file exists
$fp = fopen ($counterFile, "w");
Fputs ($FP, "0");
Fclose ($FP);
}
Read files
$n = 10;
$fp = fopen ($counterFile, "R");
$str 1 = fgets ($fp, $n);
$str 1++;
Fclose ($FP);
Write back the file
$fp = fopen ($counterFile, "w");
Fputs ($fp, $str 1);
Fclose ($FP);

?>


Program Description: In browsing to this page, the PHP program first to find the Counter.txt file exists, if it does not exist, then create a counter.txt file, and 0 write to the file. It then reads the contents of the Counter.txt file and adds a read number to it, and then writes back to the file.

2, based on the database count

Principle: Record the number of visitors in a database, when the page is visited, read out the previous number of visitors from the database, plus 1, get the latest number of visitors, and then the latest access numbers back to the database.

Implementation: Assume that the database is a MySQL database, named Xinxiku, first set up a data table count, table fields only counter a field, the default value of 0 to record the number of visitors.

<?php

Connection data
$db =mysql_connect ("localhost", "root", "");
mysql_select_db ("Xinxiku", $db);
Update number of Visitors
$result =mysql_query ("Update count Set counter=counter+1", $db);

?>


Program Description: Visitors to the page, the first connection to the database, and the number of digital section with the original value added to the update operation to achieve the increase in access number.

Second, the display of the number of notes

1, the normal text mode display

This display method is simple and can be directly exported where the number of digits is needed. The example above illustrates:

Based on the file count, the direct output variable str1 content can be.
<?php echo $str 1;?>

Based on the database count, first read out from the database, and then output.

<?php

Querying the database
$sql = "SELECT * from Count";
$result =mysql_query ($sql, $db);
To get a recordset
$record =mysql_fetch_array ($result);
Number of visits made
$str 1= $record ["Counter"];
echo $str 1;

?>


Similarly, you can use HTML statements like <font color size> to modify the output numbers. The advantage of text display is that it reduces download time and browses faster. The disadvantage is that the display mode is not lively.

2, Graphic mode display

Principle: read out the Access data format into a standard format, and then use the image processing function provided by PHP, the digital output into a picture format. In this way, the digital display format can be controlled at will, truly reflect their own characteristics.

Realize:

?
Header ("Content-type:image/gif");
Define output as Image type
$n = 10;
Variable $n is the number of displayed digits

Using the above method, get the number of visitors and assign value to the variable $str1 (Cheng)
$str 1 = value of the number of visitors
$str 2 = "";
Number of digits if not enough $n, 0 in front
$len 1 = strlen ($str 1);
for ($i =1; $i <= $n; $i + +) {
$str 2 = "0". $str 2;
};
Get $n bit 0
$len 2 = strlen ($str 2);
Count the number of digits visited
$dif = $len 2-$len 1;
$rest = substr ($str 2, 0, $DIF);
$string = $rest. $str 1;
Number of digits if not enough $n, 0 in front
For ($i =0 $i <= $n-1; $i + +) {
$str [$i]=substr ($string, $i, 1);
};
Storing each digit in an array
$font = 4;
Define font Size
$im = Imagecreate ($n *11-1,16);
New Image
$black = Imagecolorallocate ($im, 0,0,0);
$white = Imagecolorallocate ($im, 255,255,255);
Define Color
Imagefill ($im, 0,0, $black);
Set the background of the counter to black
Imagestring ($im, $font, 1,0, $str [0], $white);
For ($i =1 $i <= $n-1; $i + +) {
Imageline ($im, $i *11-1,0, $i *11-1,16, $white);
Imagestring ($im, $font, $i *11+1,0, $str [$i], $white);
};
Writes each bit to the image and separates it with a vertical bar
Imagegif ($im);
Image output
Imagedestroy ($im);
Releasing the image
?>


The output figure is as shown here:


Function Description:

imagecreate (int x_size, int y_size): Create a fully-empty graphic. Parameter x_size, Y_size is the size of the graphic, in pixels (pixel).

Imagecolorallocate (int im, int red, int green, int blue): Used to match the color of the graphic for use by other drawing functions. The parameter IM represents the handle of the graph. Parameters red, green, and blue are three primary colors of color, with values ranging from 0 to 255.

Imagefill (int im, int x, int y, int col): Color the area where the picture coordinates (X,Y) are located. The parameter col represents the color to be painted.

imagestring (int im, int font, int x, int y, string s, int col): Draw horizontal string across the picture. The argument font is a glyph, set to 1 through 5 to use the default glyph. parameter x, Y is the string start coordinate. The contents of the string are placed on the parameter S. The parameter col represents the color of the string.

Imageline (int im, int x1, int y1, int x2, int y2, int col): Draw a solid line on the graph. Connections from x1, y1 to X2, Y2, origin (0,0) are the upper-left corner of the graph. The parameter col is the color of the solid line.

Imagegif (int im, string [filename]): Create an GIF format graphic. Parameter im is a picture code created using Imagecreate ().

Imagedestroy (int im): Handle the picture and release it into memory space.

Third, concluding remarks

1, the above code if directly placed in the file header, so long as someone accesses the page, whether it is refreshed or from other pages of the site to the page, will make the count value plus 1, so that the main page count lost authenticity. There are two very simple ways to solve this problem.


A, in return to the page of the link passed a parameter flag, such as: Index.php?flag=1, before the count first check whether the flag variable has been assigned, if not assigned, the counter plus 1. Otherwise it will not be added.

if (empty ($flag)) {
$counter +=1;
}


b, with the session record a sign flag, before the number of records to determine whether the flag has been assigned, if not assigned value, then the Count plus 1, and give flag assign value, otherwise, register unchanged.

if (!isset ($flag))
{
Handling Registers plus 1 statements
...
Assign Value flag
Session_Start ();
Session_register ("flag");
$flag = 1;
}


2, in order to facilitate, you can use the counter as a function mycounter (), so that only the beginning of the home page to join require ("filename"); Make MyCounter () a part of this homepage, when needed, will be MyCounter ();? > Add to the counter where you want to show it.

3, the use of graphics display counters, where necessary directly inserted: can be. But note that PHP must install the GD library in order to take advantage of the image processing functions in PHP.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.