search
HomeBackend DevelopmentPHP TutorialThe main implementation method of generating access counters in PHP_PHP Tutorial

Now use itSome friends may think it is difficult and dare not try it. In fact, with PHP as a tool, it is not difficult, you can even say it is easy. First, let me talk about the idea of ​​a visitor counter: a visitor browses this page, and the server (such as Apache) reads the number of times the page has been viewed from a document (num.txt is used as an example below), and adds 1, then save it back to num.txt, and display the number of times plus one in the browser.

If another visitor browses this page, the server repeats the above process, thus realizing PHP to generate an access counter. PHP does not have a direct counter function, but using its powerful functions, we can easily write a counter ourselves.

Now we will explain the functions that the program needs to use:

1. Open file operation: int fopen(string filename, string mode); where string filename is the name of the file to be opened and must be in string form. For example "num.txt". String mode is the way to open the file, which must be in character form.

’r’, read-only form, the file pointer points to the beginning of the file. 'r+', readable and writable, the file pointer points to the beginning of the file. 'w', write-only form, the file pointer points to the beginning of the file, the file length is truncated to 0, if the file does not exist, an attempt will be made to create the file. 'w+', readable and writable, the file pointer points to the beginning of the file, and the file length is cut to 0. If the file does not exist, an attempt will be made to create the file.

'a', append form (can only be written), the file pointer points to the end of the file, if the file does not exist, an attempt will be made to create the file. 'a+', readable and writable, the file pointer points to the end of the file, if the file does not exist, an attempt will be made to create the file.

2. File reading operation: string fgets(int fp, int length); where int fp is the file stream pointer to read data, and the fopen function returns the value. int length is the number of characters to be read, and the actual number of characters read is length-1.

3. File writing operation: int fputs(int fp, string str, int [length]); where int fp is the file stream pointer to which information is to be written, and the value is returned by the fopen function. string str is the string to be written to the file. int length is the length to be written, optional. If length is not selected, the entire string will be written. Otherwise, write length characters.

4. Close file operation: int fclose(int fp); where int fp is the file stream pointer returned by the fopen function. Next, let’s take a look at the prototype of the access counter generated by PHP: (assuming the num.txt file exists)

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><span> ?php $</span><span class="attribute">fp</span><span> = </span><span class="attribute-value">fopen</span><span>("num.txt", "r");   </span></span></span></li>
<li><span>//只读方式打开num.txt文件   </span></li>
<li class="alt">
<span>$</span><span class="attribute">num</span><span> = </span><span class="attribute-value">fgets</span><span>($fp,5);   </span>
</li>
<li><span>//读取4位数字   </span></li>
<li class="alt"><span>$num++;   </span></li>
<li><span>//浏览次数加一   </span></li>
<li class="alt"><span>fclose($fp);   </span></li>
<li><span>//关闭文件   </span></li>
<li class="alt">
<span>$</span><span class="attribute">fp</span><span> = </span><span class="attribute-value">fopen</span><span>("num.txt", "w");   </span>
</li>
<li><span>//只写方式打开num.txt文件   </span></li>
<li class="alt"><span>fputs($fp, $str1);   </span></li>
<li><span>//写入加一后结果   </span></li>
<li class="alt"><span>fclose($fp);   </span></li>
<li><span>//关闭文件   </span></li>
<li class="alt"><span>echo "$num";   </span></li>
<li><span>//浏览器输出浏览次数  </span></li>
<li class="alt">
<span class="tag">?></span><span> </span>
</li>
</ol>

It should be noted that this is only the prototype of the counter, it can only Displaying the number of times in text is not beautiful, but PHP has extremely powerful image processing capabilities, and it can easily and dynamically generate WEB images.

The above prototype will be modified below to make it a truly practical counter. The idea behind generating an access counter in PHP is as follows: use the method in the prototype to get the number of accesses, convert the number into a standard format, perform image processing, and output it into a picture for display. If you want to generate a counting image, you need the following functions:

1. String length function: int strlen(string str); where string str is the string whose length is to be calculated.

2. Add strings: For example, add $string1 and $string2: $string = $string1.$string2

3. Create a new image function: int imagecreate(int x_size, int y_size); where x_size and y_size are the width and height of the new image (in pixels) respectively.

4. Color function: int imagecolorallocate(int im, int red, int green, int blue); where int im is the image identification number. int red, green, and blue are the components of red, green, and blue colors respectively, with a value range of 0 - 255, that is, the RGB of the corresponding color.

5. Function to fill the image with color: int imagefill(int im, int x, int y, int col); where int x, int y are the image coordinates where color filling starts, starting from the upper left corner of the image is (0, 0). int col is the identification number of the color.

6. Function to write horizontal text in an image: int imagestring(int im, int font, int x, int y, string s, int col); where int im is the identification number of the image. int font is the font identification number. int x, int y are the coordinates to start writing the font, (0,0) is the upper left corner. string s is the string to be written. int col is the color identification number of the font.

7. The function to draw a straight line in the image: int imageline(int im, int x1, int y1, int x2, int y2, int col); where int im is the identification number of the image. int x1, int y1, int x2, int y2 are the starting and ending coordinates of the drawn line. int col is the color identification number of the line.

8. Function to output image into GIF format: int imagegif(int im, string filename); where int im is the identification number of the image. String filename is the name of the generated image, optional. If filename is empty, it will be output directly.

9. Release the image: int imagedestroy(int im); where int im is the image identification number to be released. This function releases the image of the identification number im and the system resources occupied by the image. You can call this counter on your homepage like this to implement PHP to generate an access counter: The main implementation method of generating access counters in PHP_PHP Tutorial The following is the program list of counter.php3:

<ol class="dp-xml">
<li class="alt"><span><span class="tag"><span> ?   </span></span></span></li>
<li><span>Header("Content-type: image/gif");   </span></li>
<li class="alt"><span>//定义输出为图像类型   </span></li>
<li>
<span>$</span><span class="attribute">n</span><span>=</span><span class="attribute-value">10</span><span>;   </span>
</li>
<li class="alt"><span>//变量$n是显示位数   </span></li>
<li>
<span>$</span><span class="attribute">fp</span><span> = </span><span class="attribute-value">fopen</span><span>("num.txt", "r");   </span>
</li>
<li class="alt">
<span>$</span><span class="attribute">str1</span><span> = </span><span class="attribute-value">fgets</span><span>($fp,$n+1);   </span>
</li>
<li><span>$str1++; fclose($fp);   </span></li>
<li class="alt">
<span>$</span><span class="attribute">fp</span><span> = </span><span class="attribute-value">fopen</span><span>("num.txt", "w");   </span>
</li>
<li><span>fputs($fp, $str1);   </span></li>
<li class="alt"><span>fclose($fp);   </span></li>
<li><span>//同原型   </span></li>
<li class="alt">
<span>$</span><span class="attribute">str2</span><span> = "";   </span>
</li>
<li>
<span>$</span><span class="attribute">len1</span><span> = </span><span class="attribute-value">strlen</span><span>($str1);   </span>
</li>
<li class="alt">
<span>for ($</span><span class="attribute">i</span><span>=</span><span class="attribute-value">1</span><span>;$i</span><span class="tag"><span>=$n;$i++)   </span></span>
</li>
<li>
<span>{ $</span><span class="attribute">str2</span><span> = "0".$str2; };   </span>
</li>
<li class="alt"><span>//得到$n位0   </span></li>
<li>
<span>$</span><span class="attribute">len2</span><span> = </span><span class="attribute-value">strlen</span><span>($str2);   </span>
</li>
<li class="alt"><span>//计算访问人数的位数   </span></li>
<li>
<span>$</span><span class="attribute">dif</span><span> = $len2 - $len1;   </span>
</li>
<li class="alt">
<span>$</span><span class="attribute">rest</span><span> = </span><span class="attribute-value">substr</span><span>($str2, 0, $dif);   </span>
</li>
<li>
<span>$</span><span class="attribute">string</span><span> = $rest.$str1;   </span>
</li>
<li class="alt"><span>//位数如果不够$n位,在前面补0   </span></li>
<li>
<span>for ($</span><span class="attribute">i</span><span>=</span><span class="attribute-value">0</span><span>;$i</span><span class="tag"><span>=$n-1;$i++)   </span></span>
</li>
<li class="alt"><span>{ $str[$i]=substr($string,$i,1); };   </span></li>
<li><span>//以数组存储每位  </span></li>
<li class="alt">
<span> $</span><span class="attribute">font</span><span> = </span><span class="attribute-value">4</span><span>;  </span>
</li>
<li><span> //定义字号  </span></li>
<li class="alt">
<span> $</span><span class="attribute">im</span><span> = </span><span class="attribute-value">imagecreate</span><span>($n*11-1,16);   </span>
</li>
<li><span>//新建图象  </span></li>
<li class="alt">
<span> $</span><span class="attribute">black</span><span> = </span><span class="attribute-value">ImageColorAllocate</span><span>($im, 0,0,0);   </span>
</li>
<li>
<span>$</span><span class="attribute">white</span><span> = </span><span class="attribute-value">ImageColorAllocate</span><span>($im, 255,255,255);   </span>
</li>
<li class="alt"><span>//定义颜色   </span></li>
<li><span>imagefill($im, 0,0,$black);   </span></li>
<li class="alt"><span>//把计数器的底色设置成黑色   </span></li>
<li><span>ImageString($im,$font,1,0,$str[0],$white);  </span></li>
<li class="alt">
<span> for ($</span><span class="attribute">i</span><span>=</span><span class="attribute-value">1</span><span>;$i</span><span class="tag"><span>=$n-1;$i++)   </span></span>
</li>
<li><span>{ imageline($im, $i*11-1,0,$i*11-1,16, $white); ImageString($im,$font,$i*11+1,0,$str[$i],$white); };   </span></li>
<li class="alt"><span>//将每位写入图象,并以竖线分隔   </span></li>
<li><span>ImageGif($im);  </span></li>
<li class="alt"><span> //图象输出   </span></li>
<li><span>ImageDestroy($im);   </span></li>
<li class="alt"><span>//释放图象   </span></li>
<li>
<span class="tag">?></span><span>  </span>
</li>
</ol>

另外,为了方便,还可以用将计数器作为一个函数MyCounter(),这样只许需在主页开头加入require(“filename”);使MyCounter()成为此主页的一部分,需要的时候,将 MyCounter();?>加在需要计数器的地方就可以完成PHP生成访问计数器。


www.bkjia.comtruehttp://www.bkjia.com/PHPjc/446219.htmlTechArticle现在用 有的朋友可能认为它很难,不敢去尝试,其实有了PHP这个工具,它并不难,甚至可以说它很容易。 首先,让我来谈一谈访客计数器...
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How can you prevent session fixation attacks?How can you prevent session fixation attacks?Apr 28, 2025 am 12:25 AM

Effective methods to prevent session fixed attacks include: 1. Regenerate the session ID after the user logs in; 2. Use a secure session ID generation algorithm; 3. Implement the session timeout mechanism; 4. Encrypt session data using HTTPS. These measures can ensure that the application is indestructible when facing session fixed attacks.

How do you implement sessionless authentication?How do you implement sessionless authentication?Apr 28, 2025 am 12:24 AM

Implementing session-free authentication can be achieved by using JSONWebTokens (JWT), a token-based authentication system where all necessary information is stored in the token without server-side session storage. 1) Use JWT to generate and verify tokens, 2) Ensure that HTTPS is used to prevent tokens from being intercepted, 3) Securely store tokens on the client side, 4) Verify tokens on the server side to prevent tampering, 5) Implement token revocation mechanisms, such as using short-term access tokens and long-term refresh tokens.

What are some common security risks associated with PHP sessions?What are some common security risks associated with PHP sessions?Apr 28, 2025 am 12:24 AM

The security risks of PHP sessions mainly include session hijacking, session fixation, session prediction and session poisoning. 1. Session hijacking can be prevented by using HTTPS and protecting cookies. 2. Session fixation can be avoided by regenerating the session ID before the user logs in. 3. Session prediction needs to ensure the randomness and unpredictability of session IDs. 4. Session poisoning can be prevented by verifying and filtering session data.

How do you destroy a PHP session?How do you destroy a PHP session?Apr 28, 2025 am 12:16 AM

To destroy a PHP session, you need to start the session first, then clear the data and destroy the session file. 1. Use session_start() to start the session. 2. Use session_unset() to clear the session data. 3. Finally, use session_destroy() to destroy the session file to ensure data security and resource release.

How can you change the default session save path in PHP?How can you change the default session save path in PHP?Apr 28, 2025 am 12:12 AM

How to change the default session saving path of PHP? It can be achieved through the following steps: use session_save_path('/var/www/sessions');session_start(); in PHP scripts to set the session saving path. Set session.save_path="/var/www/sessions" in the php.ini file to change the session saving path globally. Use Memcached or Redis to store session data, such as ini_set('session.save_handler','memcached'); ini_set(

How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version