In php, we sometimes write a simple website page access statistician. The following section describes how to use PHP to implement counter code. I hope this method will be helpful to you.
Let's add a counter to the homepage. It is helpful to demonstrate how to read and write files and create your own functions. Counter. inc contains the following code:
The Code is as follows: |
Copy code |
<? /* | A simple counter */ Function get_hitcount ($ counter_file) { /* Returns the counter to zero. In this case, if the counter is not used, the initial value is 1. Of course, you can set the initial value to 20000 to cheat me. */ $ Count = 0; // If the stored counter file already exists, read the content If (file_exists ($ counter_file )) { $ Fp = fopen ($ counter_file, "r "); // We only took the first 20 digits. I hope your site will not be too popular. $ Count = 0 fgets ($ fp, 20 ); // Because the function fgets () returns a string, We can automatically convert it to an integer by adding 0. Fclose ($ fp ); // File operation completed } // Increase the Count value once $ Count; // Write the new count value to the file $ Fp = fopen ($ counter_file, "w "); Fputs ($ fp, $ count ); Fclose ($ fp ); # Return Count value Return ($ count ); } ?> Then we change the front. php3 file to display this counter: <? Include ("include/counter. inc "); // I put the counter value in the counter.txt file, read and Output Printf ("<CENTER> <B> d </B> </CENTER> <BR> n ", Get_hitcount ("counter.txt ")); Include ("include/footer. inc "); ?> |
Example 2
The Code is as follows: |
Copy code |
1) text counter <? Php $ Countfile = "/count.txt"; // sets the file for saving data If (! File_exists ($ countfile) {// checks whether the file exists. Exec ("echo 0> $ countfile "); } $ Fp = fopen ($ countfile, "rw "); $ Length = filesize ($ countfile ); $ Num = fgets ($ fp, $ length ); $ Num + = 1; Exec ("rm-rf $ countfile "); Exec ("echo $ num> $ countfile "); PRint "total visits:". "$ num". "times"; // display the number of visits ?> 2) graphic counters <? $ Countfile = "/count-num.txt"; // sets the file for saving the data If (! File_exists ($ countfile) // checks whether a file exists. {Exec ("echo 0> $ countfile ");} $ Fp = fopen ($ countfile, "rw "); $ Length = filesize ($ countfile ); $ Num = fgets ($ fp, $ length ); $ Num + = 1; Exec ("rm-rf $ countfile "); Exec ("echo $ num> $ countfile "); $ Len_str = strlen ($ num ); For ($ I = 0; $ I <$ len_str; $ I ++ ){ $ Each_num = substr ($ num, $ I, 1 ); $ Out_str = $ out_str. " "; } Print "total visits:". "$ out_str". "times"; // display the number of visits |