如果發現某些 ip 的用戶在網站上搗亂,可以將他/她的 ip 封殺,這不但可以停止搗亂行為,也可以減少主機的資源浪費及頻寬,以下介紹透過 PHP 及 Apache 的 .htaccess 的實現方法。
PHP
如果要阻擋的 ip 不多,可以直接加上以下一行到程式頂端:
-
<?php
-
if($_SERVER['REMOTE_ADDR'] == "192.168.1.101"){
-
}
-
?>
以上程式碼很簡單,只要檢查訪客的 ip 是否 192.168.1.101,如果正確則結束程式罷了,但這樣的問題是當要阻擋的 ip 數量增多時,需要每次都在以上程式碼上加上 ip,要維護很不方便。以下的方法是使用文字檔儲存了要阻擋的 ip,每一行一筆資料,檔案為 ban_ip_list.dat,實現方法如下:
以上第一包是從 ban_ip_list.dat 讀入每一行資料,並儲存到 $banned 陣列內,然後用 in_array() 檢查訪客的 ip 如果在陣列內,則印出 "You have been banned.",並且結束程式。
.htaccess
如果網站不是用 PHP 寫成,或者因為頁數很多,不想每個 PHP 程式逐一修改的話,可以用 .htaccess,只要在網站的根目錄建立一個 .htaccess 檔案 (如果已經存在則不用建立),加上以下內容即可:
Order Deny,Allow
Deny from xxx.xxx.xxx.xxx
Deny from xxx.xxx.xxx
這種方法可以限制特定 ip 或網段。
PHP with file(’.htaccess’)?
dyn add/delete && save resources?
Comment by Leon — March 15, 2006 @ 2:45 am
Yes, but you cannot using file() to add/edit/delete the entry from .htaccess, you have using fopen() and fwrite() to do that.
And you have to make sure the permission of .htaccess is writeable by web server.
Comment by Sam Tang — March 15, 2006 @ 9:12 am
There has a solution about PHP work with .htaccess files.
try to take a view about the PHP class.
http://www.phpclasses.org/browse/package/411.html
Comment by Kapar Shu — March 21, 2006 @ 2:34 am