php SQL 防注入的一些經驗

來源:互聯網
上載者:User
原文 http://www.cnblogs.com/liuzhang/p/4753467.html

產生原因

一方面自己沒這方面的意識,有些資料沒有經過嚴格的驗證,然後直接拼接 SQL 去查詢。導致漏洞產生,比如:

$id = $_GET['id'];  $sql = "SELECT name FROM users WHERE id = $id";

因為沒有對 $_GET['id'] 做資料類型驗證,注入者可提交任何類型的資料,比如 " and 1= 1 or " 等不安全的資料。如果按照下面方式寫,就安全一些。

$id = intval($_GET['id']);  $sql = "SELECT name FROM users WHERE id = $id";

把 id 轉換成 int 類型,就可以去掉不安全的東西。

驗證資料

防止注入的第一步就是驗證資料,可以根據相應類型進行嚴格的驗證。比如 int 類型直接同過 intval 進行轉換就行:

$id =intval( $_GET['id']);

字元處理起來比較複雜些,首先通過 sprintf 函數格式話輸出,確保它是一個字串。然後通過一些安全函數去掉一些不合法的字元,比如:

$str = addslashes(sprintf("%s",$str)); //也可以用 mysqli_real_escape_string 函數替代addslashes

這樣處理以後會比較安全。當然還可以進一步去判斷字串長度,去防止「 緩衝區溢位攻擊 」比如:

$str = addslashes(sprintf("%s",$str));  $str = substr($str,0,40); //最大長度為40

參數化綁定

參數化綁定,防止 SQL 注入的又一道屏障。php MySQLi 和 PDO 均提供這樣的功能。比如 MySQLi 可以這樣去查詢:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");$code = 'DEU';$language = 'Bavarian';$official = "F";$percent = 11.2;$stmt->bind_param('sssd', $code, $language, $official, $percent);

PDO 的更是方便,比如:

/* Execute a prepared statement by passing an array of values */$sql = 'SELECT name, colour, calories  FROM fruit  WHERE calories < :calories AND colour = :colour'; $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));$sth->execute(array(':calories' => 150, ':colour' => 'red'));$red = $sth->fetchAll();$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));$yellow = $sth->fetchAll();

我們多數使用 php 的架構進行編程,所以最好不要自己拼字 SQL,按照架構給定參數綁定進行查詢。遇到較為複雜的 SQL 陳述式,一定要自己拼字的時候,一定要注意嚴格的判斷。沒有用 PDO 或者 MySQLi 也可以自己寫個 prepared,比如 wordprss db 查詢語句,可以看出也是經過嚴格的類型驗證。
function prepare( $query, $args ) {  if ( is_null( $query ) )     return;  // This is not meant to be foolproof --        but it will catch obviously incorrect usage.  if ( strpos( $query, '%' ) === false ) {     _doing_it_wrong( 'wpdb::prepare' ,      sprintf ( __( 'The query argument of %s         must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );   }  $args = func_get_args();  array_shift( $args );  // If args were passed as an array (as in vsprintf), move them up  if ( isset( $args[ 0] ) && is_array( $args[0]) )     $args = $args [0];  $query = str_replace( "'%s'", '%s' , $query );     // in case someone mistakenly already singlequoted it  $query = str_replace( '"%s"', '%s' , $query );     // doublequote unquoting  $query = preg_replace( '|(?  

總結

安全性很重要,也可以看出一個人基本功,項目漏洞百出,擴充性和可維護性再好也沒有用。平時多留意,樹立安全意識,養成一種習慣,一些基本的安全當然也不會佔用用 coding 的時間。養成這個習慣,即便在項目急,時間短的情況一下,依然可以做的品質很高。不要等到自己以後負責的東西,資料庫都被拿走了,造成損失才重視。共勉!

  • 聯繫我們

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