php中用memcached實現頁面防重新整理功能_php技巧

來源:互聯網
上載者:User

有個新需求要加上去,防止使用者頻繁重新整理頁面。具體需求是當使用者在一分鐘之後內請求指定的頁面超過100次,就直接拒絕請求。仔細分析後發現這個功能用memcache來做最方便:

1、以使用者IP和被請求的檔案名稱作為KEY值。

2、以memcached的方法increment()來自增記錄使用者訪問次數,increment()是原子性增加,準確。

3、設定set()時指定到期時間為60s,這樣就統計一分鐘的訪問次數。

於是寫了個函數放在項目的初始設定檔案中調用,函數內容如下:

function requestCount(){  $patharr = pathinfo($_SERVER['PHP_SELF']); $filename = explode('?',$patharr['basename']);//擷取當前檔案名稱 if( in_array($filename['0'],array('index.php','login.php','password.php')) ){ global $memcache; $clientip = get_client_ip(); //使用長整型IP和檔案名稱產生KEY $ipkey = 'C'.sprintf("%u", ip2long( $clientip )). $filename['0'] ; if( $visitCount = $memcache->get($ipkey) ){        if($visitCount == 100){        die('<h1>Please don\'t refresh your page!</h1>');      }else{        $memcache->increment($ipkey);      }   }else{    $memcache->set($ipkey,1,0,60); } }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.