PHP在使用Regex驗證,防注入的時候要注意一下的細節

來源:互聯網
上載者:User

標籤:

如下:這是一個防止使用者輸入的資料中包含SQL的一些關鍵字的Regex

        之前一直認為這寫的很正確,沒多大的問題,而且自己測試也沒問題,

    因為關鍵字包含 And,而如果使用者輸入andy的時候呢,汗,所以還得結合

    SQL的一些特點來對這個Regex進行修改

 

註:\s:在Regex中表示空格;Regex最後的小"i"表示不區分大小寫

做出的修改是:select,insert,update,delete這幾個關鍵字,使用的時候前面有可能有或沒有空格,但後面必須有一個空格,

                   所以變成 [\s]*select\s

                 而and,or,union這些,因為必須前面一個空格,後面一個空格才會生效

                   所以改成 \sand\s

 

function inject_check($Sql_Str) {//檢查Sql的注入語句,各種關鍵字。

       //原來是這樣的:/select|insert|update|delete|and|or|\‘|\\*|\*|\.\.\/|\.\/|union|into|load_file|outfile/i
      //$check=preg_match(‘/[\s]*select\s|[\s]*insert\s|[\s]*update\s|                        [\s]*delete\s|\sand\s|\sor\s|\‘|\\*|\*|\.\.\/|\.\/|\sunion\s|\sinto\s|load_file|outfile/i‘,$Sql_Str);

       //不過這樣太難看了,所以稍微修改一下,

         $check=preg_match(‘/[\s]*(select|insert|update|delete)\s|\s(and|or|join|like|regexp|where|union|into)\s|\#|\‘|\\*|\*|\.\.\/|\.\/|load_file|outfile/i‘,$Sql_Str);
      if ($check) {
           echo ‘<script language="JavaScript">alert("Warnning!!\r\n‘.$Sql_Str.‘ is invalid.");</script>‘;
           exit();
     }else{
          return $Sql_Str;
     }
}

 

 

PHP在使用Regex驗證,防注入的時候要注意一下的細節

聯繫我們

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