在防止sql注入這些細節出現問題的一般是那些大意的程式員或者是新手程式員,他們由於沒有對使用者提交過來的資料進行一些必要的過濾,從而導致了給大家測試的時候一下就攻破了你的資料庫,下面我們來簡單的介紹一個使用者登入未進行安全配置可能出現的sql注入方法,下面一起來看看吧。
比如以下一段登入的代碼:
if($l = @mysql_connect('localhost', 'root', '123')) or die('資料庫連接失敗');mysql_select_db('test');mysql_set_charset('utf8');$sql = 'select * from test where username = "$username" and password = "$password"';$res = mysql_query($sql);if(mysql_num_rows($res)){header('Location:./home.php');}else{die('輸入有誤');}
注意上面的sql語句,存在很大的安全隱患,如果使用以下萬能密碼和萬能使用者名稱,那麼可以輕鬆進入頁面:
$sql = 'select * from test where username = "***" and password = "***" or 1 = "1"';
很明顯,針對這條sql語句的萬能密碼是: ***" or 1 = "1
$sql = 'select * from test where username ="***" union select * from users/* and password = "***"';
正斜線* 表示後面的不執行,mysql支援union聯集查詢,因此直接查詢出所有資料; 所以針對這條sql語句的萬能使用者名稱是:***" union select * from users/*
但是,此注入只針對代碼中的sql語句,如果
$sql = "select * from test where username = $username and password = $password";
上面的注入至少已經不管用了,不過方法是一樣的;
在使用PDO之後,sql注入完全可以被避免,而且在這個快速開發的時代,架構橫行,已然不用過多考慮sql注入問題了。
下面整理了兩個防止sql註冊函數
/* 過濾所有GET過來變數 */foreach ($_GET as $get_key=>$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;}
另外還有一些部落格會這樣寫
<?php function post_check($post) { if (!get_magic_quotes_gpc()) // 判斷magic_quotes_gpc是否為開啟 { $post = addslashes($post); // 進行magic_quotes_gpc沒有開啟的情況對提交資料的過濾 } $post = str_replace("_", "\_", $post); // 把 '_'過濾掉 $post = str_replace("%", "\%", $post); // 把' % '過濾掉 $post = nl2br($post); // 斷行符號轉換 $post= htmlspecialchars($post); // html標記轉換 return $post; } ?>
http://www.bkjia.com/PHPjc/824734.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/824734.htmlTechArticle在防止sql注入這些細節出現問題的一般是那些大意的程式員或者是新手程式員,他們由於沒有對使用者提交過來的資料進行一些必要的過濾,...