PHP網站中整體防注入方法

來源:互聯網
上載者:User

/*
 * Author: heiyeluren
 * Date: 2005-7-20
 * Blog: http://blog.csdn.net/heiyeshuwu
*/

今天寫代碼的時候猛然想到是不能能夠通過一個檔案來處理整個網站中所有可能出現注入的地方進行防範呢?這樣就能夠不用在每個程式裡對每個變數進行過濾,節省了時間和代碼。

我們主要是從兩點出發,因為我們的擷取的變數一般都是通過GET或者POST方式提交過來的,那麼我們只要對GET和POST過來的變數進行過濾,那麼就能夠達到防止注入的效果。而且我們的PHP真是非常好,已經內建了$_GET和$_POST兩個數組來儲存所有變數,我們要做的工作就是過濾每個變數就可以了。

下面看具體的代碼:

/* Author: heiyeluren */
/* 過濾所有GET過來變數 */
foreach ($_GET as $get_key=>$get_var)
{
    if (is_numeric($get_var))
 if (is_numeric($get_var)) {
  $get[strtolower($get_key)] = get_int($get_var);
 } else {
  $get[strtolower($get_key)] = get_str($get_var);
 }
}

/* 過濾所有POST過來的變數 */
foreach ($_POST as $post_key=>$post_var)
{
 if (is_numeric($post_var)) {
  $post[strtolower($post_key)] = get_int($post_var);
 } else {
  $post[strtolower($post_key)] = get_str($post_var);
 }
}

/* 過濾函數 */
//整型過濾函數
function get_int($number)
{
    return intval($number);
}
//字串型過濾函數
function get_str($string)
{
    if (!get_magic_quotes_gpc()) {
 return addslashes($string);
    }
    return $string;
}

那麼我們把以上代碼放到一個公用的檔案裡,比如security.inc.php裡面,每個檔案裡都include一下這個檔案,那麼就能夠給任何一個程式進行提交的所有變數進行過濾了,就達到了我們一勞永逸的效果。

另外,還有一些其他的過濾方法,比如採用我以前使用的關鍵字過濾的方法:http://dev.csdn.net/article/71/71475.shtm
還可以參考三尺寒冰寫的方法:http://www.fanghei.com/html/2005-06/20050607114008.htm

方法是不同的,但是核心就是為了我們的代碼更加安全。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.