Using memcached in PHP to implement page anti-refresh function _php skill

Source: Internet
Author: User

There is a new need to add to prevent users from frequently refreshing the page. The specific requirement is that when the user requests the specified page more than 100 times in a minute, the request is rejected directly. After careful analysis, it is found that this function is most convenient to use memcache:

1, the User IP and the requested filename as the key value.

2, in the Memcached Method increment () from the increased number of user visits, increment () is an increase in atomicity, accurate.

3. Setting set () specifies an expiration time of 60s, which counts the number of visits per minute.

So I wrote a function called in the initialization file of the project, and the function reads as follows:

function RequestCount () { 

 $patharr = pathinfo ($_server[' php_self '));

 $filename = Explode ('? ', $patharr [' basename '])//Get the current file name

 if (In_array ($filename [' 0 '],array (' index.php '), ' Login.php ', ' password.php ')) {

 Global $memcache;

 $clientip = Get_client_ip ();

 Use long integer IP and filename to generate key

 $ipkey = ' C '. sprintf ("%u", Ip2long ($clientip)). $filename [' 0];

 if ($visitCount = $memcache->get ($ipkey)) {  

      if ($visitCount =) {

        die ('  

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.