方法:php
一、預處理。(預處理語句針對SQL注入是很是有用的,由於參數值發送後使用不一樣的協議,保證了數據的合法性。)html
二、mysql_real_escape_string -- 轉義 SQL 語句中使用的字符串中的特殊字符,並考慮到鏈接的當前字符集 !mysql
$sql = "select count(*) as ctr from users where username ='".mysql_real_escape_string($username)."' and password='". mysql_real_escape_string($pw)."' limit 1";
三、打開magic_quotes_gpc來防止SQL注入。php.ini中有一個設置:magic_quotes_gpc = Off這個默認是關閉的,若是它打開後將自動把用戶提交對sql的查詢進行轉換,好比把 ' 轉爲 \'等,對於防止sql注射有重大做用。sql
若是magic_quotes_gpc=Off,則使用addslashes()函數。函數
四、自定義函數:post
/** * 防止sql注入自定義方法一 * author: xiaochuan * @param: mixed $value 參數值 */ function check_param($value=null) { # select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile $str = 'select|insert|and|or|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile'; if(!$value) { exit('沒有參數!'); }elseif(eregi($str, $value)) { exit('參數非法!'); } return true; } /** * 防止sql注入自定義方法二 * author: xiaochuan * @param: mixed $value 參數值 */ function str_check( $value ) { if(!get_magic_quotes_gpc()) { // 進行過濾 $value = addslashes($value); } $value = str_replace("_", "\_", $value); $value = str_replace("%", "\%", $value); return $value; } /** * 防止sql注入自定義方法三 * author: xiaochuan * @param: mixed $value 參數值 */ function post_check($value) { if(!get_magic_quotes_gpc()) { // 進行過濾 $value = addslashes($value); } $value = str_replace("_", "\_", $value); $value = str_replace("%", "\%", $value); $value = nl2br($value); $value = htmlspecialchars($value); return $value; }