PHP simple counter instance program. 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. In php, we sometimes write simple website page access statistical tools. the following small series will introduce you to counter code using PHP. 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: |
|
/* | 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 (" D N ", Get_hitcount ("counter.txt ")); Include ("include/footer. inc "); ?> |
Example 2
The code is as follows: |
|
1) text counter $ 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 |
Bytes. Let's...